2 // Copyright © 2020 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
6 #include "BasePipeServer.hpp"
8 #include "common/include/Constants.hpp"
11 #include <boost/cast.hpp>
16 using namespace armnnUtils;
18 namespace armnnProfiling
21 bool BasePipeServer::ReadFromSocket(uint8_t* packetData, uint32_t expectedLength)
23 // This is a blocking read until either expectedLength has been received or an error is detected.
24 long totalBytesRead = 0;
25 while (boost::numeric_cast<uint32_t>(totalBytesRead) < expectedLength)
27 long bytesRead = Sockets::Read(m_ClientConnection, packetData, expectedLength);
30 std::cerr << ": Failure when reading from client socket: " << strerror(errno) << std::endl;
35 std::cerr << ": EOF while reading from client socket." << std::endl;
38 totalBytesRead += bytesRead;
43 bool BasePipeServer::WaitForStreamMetaData()
47 std::cout << "Waiting for stream meta data..." << std::endl;
49 // The start of the stream metadata is 2x32bit words, 0 and packet length.
51 if (!ReadFromSocket(header, 8))
55 EchoPacket(PacketDirection::ReceivedHeader, header, 8);
56 // The first word, stream_metadata_identifer, should always be 0.
57 if (ToUint32(&header[0], TargetEndianness::BeWire) != 0)
59 std::cerr << ": Protocol error. The stream_metadata_identifer was not 0." << std::endl;
64 if (!ReadFromSocket(pipeMagic, 4))
68 EchoPacket(PacketDirection::ReceivedData, pipeMagic, 4);
70 // Before we interpret the length we need to read the pipe_magic word to determine endianness.
71 if (ToUint32(&pipeMagic[0], TargetEndianness::BeWire) == armnnProfiling::PIPE_MAGIC)
73 m_Endianness = TargetEndianness::BeWire;
75 else if (ToUint32(&pipeMagic[0], TargetEndianness::LeWire) == armnnProfiling::PIPE_MAGIC)
77 m_Endianness = TargetEndianness::LeWire;
81 std::cerr << ": Protocol read error. Unable to read PIPE_MAGIC value." << std::endl;
84 // Now we know the endianness we can get the length from the header.
85 // Remember we already read the pipe magic 4 bytes.
86 uint32_t metaDataLength = ToUint32(&header[4], m_Endianness) - 4;
87 // Read the entire packet.
88 std::vector<uint8_t> packetData(metaDataLength);
90 boost::numeric_cast<uint32_t>(Sockets::Read(m_ClientConnection, packetData.data(), metaDataLength)))
92 std::cerr << ": Protocol read error. Data length mismatch." << std::endl;
95 EchoPacket(PacketDirection::ReceivedData, packetData.data(), metaDataLength);
96 m_StreamMetaDataVersion = ToUint32(&packetData[0], m_Endianness);
97 m_StreamMetaDataMaxDataLen = ToUint32(&packetData[4], m_Endianness);
98 m_StreamMetaDataPid = ToUint32(&packetData[8], m_Endianness);
103 armnn::profiling::Packet BasePipeServer::WaitForPacket(uint32_t timeoutMs)
105 // Is there currently more than a headers worth of data waiting to be read?
107 Sockets::Ioctl(m_ClientConnection, FIONREAD, &bytes_available);
108 if (bytes_available > 8)
110 // Yes there is. Read it:
111 return ReceivePacket();
115 // No there's not. Poll for more data.
116 struct pollfd pollingFd[1]{};
117 pollingFd[0].fd = m_ClientConnection;
118 int pollResult = Sockets::Poll(pollingFd, 1, static_cast<int>(timeoutMs));
124 throw armnn::RuntimeException(std::string("File descriptor reported an error during polling: ") +
129 throw armnn::TimeoutException("Timeout while waiting to receive packet.");
131 // Normal poll return. It could still contain an error signal
133 // Check if the socket reported an error
134 if (pollingFd[0].revents & (POLLNVAL | POLLERR | POLLHUP))
136 if (pollingFd[0].revents == POLLNVAL)
138 throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLNVAL"));
140 if (pollingFd[0].revents == POLLERR)
142 throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLERR: ") +
145 if (pollingFd[0].revents == POLLHUP)
147 throw armnn::RuntimeException(std::string("Connection closed by remote client: POLLHUP"));
151 // Check if there is data to read
152 if (!(pollingFd[0].revents & (POLLIN)))
154 // This is a corner case. The socket as been woken up but not with any data.
155 // We'll throw a timeout exception to loop around again.
156 throw armnn::TimeoutException("File descriptor was polled but no data was available to receive.");
158 return ReceivePacket();
163 armnn::profiling::Packet BasePipeServer::ReceivePacket()
166 if (!ReadHeader(header))
168 return armnn::profiling::Packet();
170 // Read data_length bytes from the socket.
171 std::unique_ptr<unsigned char[]> uniquePacketData = std::make_unique<unsigned char[]>(header[1]);
172 unsigned char* packetData = reinterpret_cast<unsigned char*>(uniquePacketData.get());
174 if (!ReadFromSocket(packetData, header[1]))
176 return armnn::profiling::Packet();
179 EchoPacket(PacketDirection::ReceivedData, packetData, header[1]);
181 // Construct received packet
182 armnn::profiling::Packet packetRx = armnn::profiling::Packet(header[0], header[1], uniquePacketData);
185 std::cout << "Processing packet ID= " << packetRx.GetPacketId() << " Length=" << packetRx.GetLength()
192 bool BasePipeServer::SendPacket(uint32_t packetFamily, uint32_t packetId, const uint8_t* data, uint32_t dataLength)
194 // Construct a packet from the id and data given and send it to the client.
195 // Encode the header.
197 header[0] = packetFamily << 26 | packetId << 16;
198 header[1] = dataLength;
199 // Add the header to the packet.
200 std::vector<uint8_t> packet(8 + dataLength);
201 InsertU32(header[0], packet.data(), m_Endianness);
202 InsertU32(header[1], packet.data() + 4, m_Endianness);
203 // And the rest of the data if there is any.
206 memcpy((packet.data() + 8), data, dataLength);
208 EchoPacket(PacketDirection::Sending, packet.data(), packet.size());
209 if (-1 == armnnUtils::Sockets::Write(m_ClientConnection, packet.data(), packet.size()))
211 std::cerr << ": Failure when writing to client socket: " << strerror(errno) << std::endl;
217 bool BasePipeServer::ReadHeader(uint32_t headerAsWords[2])
219 // The header will always be 2x32bit words.
221 if (!ReadFromSocket(header, 8))
225 EchoPacket(PacketDirection::ReceivedHeader, header, 8);
226 headerAsWords[0] = ToUint32(&header[0], m_Endianness);
227 headerAsWords[1] = ToUint32(&header[4], m_Endianness);
231 void BasePipeServer::EchoPacket(PacketDirection direction, uint8_t* packet, size_t lengthInBytes)
233 // If enabled print the contents of the data packet to the console.
236 if (direction == PacketDirection::Sending)
238 std::cout << "TX " << std::dec << lengthInBytes << " bytes : ";
240 else if (direction == PacketDirection::ReceivedHeader)
242 std::cout << "RX Header " << std::dec << lengthInBytes << " bytes : ";
246 std::cout << "RX Data " << std::dec << lengthInBytes << " bytes : ";
248 for (unsigned int i = 0; i < lengthInBytes; i++)
252 std::cout << std::endl;
254 std::cout << "0x" << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned int>(packet[i])
257 std::cout << std::endl;
261 uint32_t BasePipeServer::ToUint32(uint8_t* data, TargetEndianness endianness)
263 // Extract the first 4 bytes starting at data and push them into a 32bit integer based on the
264 // specified endianness.
265 if (endianness == TargetEndianness::BeWire)
267 return static_cast<uint32_t>(data[0]) << 24 | static_cast<uint32_t>(data[1]) << 16 |
268 static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]);
272 return static_cast<uint32_t>(data[3]) << 24 | static_cast<uint32_t>(data[2]) << 16 |
273 static_cast<uint32_t>(data[1]) << 8 | static_cast<uint32_t>(data[0]);
277 void BasePipeServer::InsertU32(uint32_t value, uint8_t* data, TargetEndianness endianness)
279 // Take the bytes of a 32bit integer and copy them into char array starting at data considering
280 // the endianness value.
281 if (endianness == TargetEndianness::BeWire)
283 *data = static_cast<uint8_t>((value >> 24) & 0xFF);
284 *(data + 1) = static_cast<uint8_t>((value >> 16) & 0xFF);
285 *(data + 2) = static_cast<uint8_t>((value >> 8) & 0xFF);
286 *(data + 3) = static_cast<uint8_t>(value & 0xFF);
290 *(data + 3) = static_cast<uint8_t>((value >> 24) & 0xFF);
291 *(data + 2) = static_cast<uint8_t>((value >> 16) & 0xFF);
292 *(data + 1) = static_cast<uint8_t>((value >> 8) & 0xFF);
293 *data = static_cast<uint8_t>(value & 0xFF);
297 } // namespace armnnProfiling