xref: /aosp_15_r20/external/armnn/profiling/server/src/basePipeServer/BasePipeServer.cpp (revision 89c4ff92f2867872bb9e2354d150bf0c8c502810)
1 //
2 // Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 
6 #include <server/include/basePipeServer/BasePipeServer.hpp>
7 
8 #include <common/include/Constants.hpp>
9 #include <common/include/NumericCast.hpp>
10 
11 #include <iostream>
12 #include <vector>
13 #include <iomanip>
14 #include <string.h>
15 
16 namespace arm
17 {
18 
19 namespace pipe
20 {
21 
ReadFromSocket(uint8_t * packetData,uint32_t expectedLength)22 bool BasePipeServer::ReadFromSocket(uint8_t* packetData, uint32_t expectedLength)
23 {
24     // This is a blocking read until either expectedLength has been received or an error is detected.
25     long totalBytesRead = 0;
26     while (arm::pipe::numeric_cast<uint32_t>(totalBytesRead) < expectedLength)
27     {
28         long bytesRead = arm::pipe::Read(m_ClientConnection, packetData, expectedLength);
29         if (bytesRead < 0)
30         {
31             std::cerr << ": Failure when reading from client socket: " << strerror(errno) << std::endl;
32             return false;
33         }
34         if (bytesRead == 0)
35         {
36             std::cerr << ": EOF while reading from client socket." << std::endl;
37             return false;
38         }
39         totalBytesRead += bytesRead;
40     }
41     return true;
42 };
43 
WaitForStreamMetaData()44 bool BasePipeServer::WaitForStreamMetaData()
45 {
46     if (m_EchoPackets)
47     {
48         std::cout << "Waiting for stream meta data..." << std::endl;
49     }
50     // The start of the stream metadata is 2x32bit words, 0 and packet length.
51     uint8_t header[8];
52     if (!ReadFromSocket(header, 8))
53     {
54         return false;
55     }
56     EchoPacket(PacketDirection::ReceivedHeader, header, 8);
57     // The first word, stream_metadata_identifer, should always be 0.
58     if (ToUint32(&header[0], TargetEndianness::BeWire) != 0)
59     {
60         std::cerr << ": Protocol error. The stream_metadata_identifer was not 0." << std::endl;
61         return false;
62     }
63 
64     uint8_t pipeMagic[4];
65     if (!ReadFromSocket(pipeMagic, 4))
66     {
67         return false;
68     }
69     EchoPacket(PacketDirection::ReceivedData, pipeMagic, 4);
70 
71     // Before we interpret the length we need to read the pipe_magic word to determine endianness.
72     if (ToUint32(&pipeMagic[0], TargetEndianness::BeWire) == PIPE_MAGIC)
73     {
74         m_Endianness = TargetEndianness::BeWire;
75     }
76     else if (ToUint32(&pipeMagic[0], TargetEndianness::LeWire) == PIPE_MAGIC)
77     {
78         m_Endianness = TargetEndianness::LeWire;
79     }
80     else
81     {
82         std::cerr << ": Protocol read error. Unable to read the PIPE_MAGIC value." << std::endl;
83         return false;
84     }
85     // Now we know the endianness we can get the length from the header.
86     // Remember we already read the pipe magic 4 bytes.
87     uint32_t metaDataLength = ToUint32(&header[4], m_Endianness) - 4;
88     // Read the entire packet.
89     std::vector<uint8_t> packetData(metaDataLength);
90     if (metaDataLength !=
91         arm::pipe::numeric_cast<uint32_t>(arm::pipe::Read(m_ClientConnection, packetData.data(), metaDataLength)))
92     {
93         std::cerr << ": Protocol read error. Data length mismatch." << std::endl;
94         return false;
95     }
96     EchoPacket(PacketDirection::ReceivedData, packetData.data(), metaDataLength);
97     m_StreamMetaDataVersion    = ToUint32(&packetData[0], m_Endianness);
98     m_StreamMetaDataMaxDataLen = ToUint32(&packetData[4], m_Endianness);
99     m_StreamMetaDataPid        = ToUint32(&packetData[8], m_Endianness);
100 
101     return true;
102 }
103 
WaitForPacket(uint32_t timeoutMs)104 arm::pipe::Packet BasePipeServer::WaitForPacket(uint32_t timeoutMs)
105 {
106     // Is there currently more than a headers worth of data waiting to be read?
107     int bytes_available;
108     arm::pipe::Ioctl(m_ClientConnection, FIONREAD, &bytes_available);
109     if (bytes_available > 8)
110     {
111         // Yes there is. Read it:
112         return ReceivePacket();
113     }
114     else
115     {
116         // No there's not. Poll for more data.
117         struct pollfd pollingFd[1]{};
118         pollingFd[0].fd = m_ClientConnection;
119         int pollResult  = arm::pipe::Poll(pollingFd, 1, static_cast<int>(timeoutMs));
120 
121         switch (pollResult)
122         {
123             // Error
124             case -1:
125                 throw ProfilingException(std::string("File descriptor reported an error during polling: ") +
126                                          strerror(errno));
127 
128                 // Timeout
129             case 0:
130                 throw arm::pipe::TimeoutException("Timeout while waiting to receive packet.");
131 
132                 // Normal poll return. It could still contain an error signal
133             default:
134                 // Check if the socket reported an error
135                 if (pollingFd[0].revents & (POLLNVAL | POLLERR | POLLHUP))
136                 {
137                     if (pollingFd[0].revents == POLLNVAL)
138                     {
139                         throw arm::pipe::ProfilingException(
140                             std::string("Error while polling receiving socket: POLLNVAL"));
141                     }
142                     if (pollingFd[0].revents == POLLERR)
143                     {
144                         throw arm::pipe::ProfilingException(
145                             std::string("Error while polling receiving socket: POLLERR: ") + strerror(errno));
146                     }
147                     if (pollingFd[0].revents == POLLHUP)
148                     {
149                         throw arm::pipe::ProfilingException(
150                             std::string("Connection closed by remote client: POLLHUP"));
151                     }
152                 }
153 
154                 // Check if there is data to read
155                 if (!(pollingFd[0].revents & (POLLIN)))
156                 {
157                     // This is a corner case. The socket as been woken up but not with any data.
158                     // We'll throw a timeout exception to loop around again.
159                     throw arm::pipe::TimeoutException(
160                         "File descriptor was polled but no data was available to receive.");
161                 }
162                 return ReceivePacket();
163         }
164     }
165 }
166 
ReceivePacket()167 arm::pipe::Packet BasePipeServer::ReceivePacket()
168 {
169     uint32_t header[2];
170     if (!ReadHeader(header))
171     {
172         return arm::pipe::Packet();
173     }
174     // Read data_length bytes from the socket.
175     std::unique_ptr<unsigned char[]> uniquePacketData = std::make_unique<unsigned char[]>(header[1]);
176     unsigned char* packetData                         = reinterpret_cast<unsigned char*>(uniquePacketData.get());
177 
178     if (!ReadFromSocket(packetData, header[1]))
179     {
180         return arm::pipe::Packet();
181     }
182 
183     EchoPacket(PacketDirection::ReceivedData, packetData, header[1]);
184 
185     // Construct received packet
186     arm::pipe::Packet packetRx = arm::pipe::Packet(header[0], header[1], uniquePacketData);
187     if (m_EchoPackets)
188     {
189         std::cout << "Processing packet ID= " << packetRx.GetPacketId() << " Length=" << packetRx.GetLength()
190                   << std::endl;
191     }
192 
193     return packetRx;
194 }
195 
SendPacket(uint32_t packetFamily,uint32_t packetId,const uint8_t * data,uint32_t dataLength)196 bool BasePipeServer::SendPacket(uint32_t packetFamily, uint32_t packetId, const uint8_t* data, uint32_t dataLength)
197 {
198     // Construct a packet from the id and data given and send it to the client.
199     // Encode the header.
200     uint32_t header[2];
201     header[0] = packetFamily << 26 | packetId << 16;
202     header[1] = dataLength;
203     // Add the header to the packet.
204     std::vector<uint8_t> packet(8 + dataLength);
205     InsertU32(header[0], packet.data(), m_Endianness);
206     InsertU32(header[1], packet.data() + 4, m_Endianness);
207     // And the rest of the data if there is any.
208     if (dataLength > 0)
209     {
210         memcpy((packet.data() + 8), data, dataLength);
211     }
212     EchoPacket(PacketDirection::Sending, packet.data(), packet.size());
213     if (-1 == arm::pipe::Write(m_ClientConnection, packet.data(), packet.size()))
214     {
215         std::cerr  << ": Failure when writing to client socket: " << strerror(errno) << std::endl;
216         return false;
217     }
218     return true;
219 }
220 
ReadHeader(uint32_t headerAsWords[2])221 bool BasePipeServer::ReadHeader(uint32_t headerAsWords[2])
222 {
223     // The header will always be 2x32bit words.
224     uint8_t header[8];
225     if (!ReadFromSocket(header, 8))
226     {
227         return false;
228     }
229     EchoPacket(PacketDirection::ReceivedHeader, header, 8);
230     headerAsWords[0] = ToUint32(&header[0], m_Endianness);
231     headerAsWords[1] = ToUint32(&header[4], m_Endianness);
232     return true;
233 }
234 
EchoPacket(PacketDirection direction,uint8_t * packet,size_t lengthInBytes)235 void BasePipeServer::EchoPacket(PacketDirection direction, uint8_t* packet, size_t lengthInBytes)
236 {
237     // If enabled print the contents of the data packet to the console.
238     if (m_EchoPackets)
239     {
240         if (direction == PacketDirection::Sending)
241         {
242             std::cout << "TX " << std::dec << lengthInBytes << " bytes : ";
243         }
244         else if (direction == PacketDirection::ReceivedHeader)
245         {
246             std::cout << "RX Header " << std::dec << lengthInBytes << " bytes : ";
247         }
248         else
249         {
250             std::cout << "RX Data " << std::dec << lengthInBytes << " bytes : ";
251         }
252         for (unsigned int i = 0; i < lengthInBytes; i++)
253         {
254             if ((i % 10) == 0)
255             {
256                 std::cout << std::endl;
257             }
258             std::cout << "0x" << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned int>(packet[i])
259                       << " ";
260         }
261         std::cout << std::endl;
262     }
263 }
264 
ToUint32(uint8_t * data,TargetEndianness endianness)265 uint32_t BasePipeServer::ToUint32(uint8_t* data, TargetEndianness endianness)
266 {
267     // Extract the first 4 bytes starting at data and push them into a 32bit integer based on the
268     // specified endianness.
269     if (endianness == TargetEndianness::BeWire)
270     {
271         return static_cast<uint32_t>(data[0]) << 24 | static_cast<uint32_t>(data[1]) << 16 |
272                static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]);
273     }
274     else
275     {
276         return static_cast<uint32_t>(data[3]) << 24 | static_cast<uint32_t>(data[2]) << 16 |
277                static_cast<uint32_t>(data[1]) << 8 | static_cast<uint32_t>(data[0]);
278     }
279 }
280 
InsertU32(uint32_t value,uint8_t * data,TargetEndianness endianness)281 void BasePipeServer::InsertU32(uint32_t value, uint8_t* data, TargetEndianness endianness)
282 {
283     // Take the bytes of a 32bit integer and copy them into char array starting at data considering
284     // the endianness value.
285     if (endianness == TargetEndianness::BeWire)
286     {
287         *data       = static_cast<uint8_t>((value >> 24) & 0xFF);
288         *(data + 1) = static_cast<uint8_t>((value >> 16) & 0xFF);
289         *(data + 2) = static_cast<uint8_t>((value >> 8) & 0xFF);
290         *(data + 3) = static_cast<uint8_t>(value & 0xFF);
291     }
292     else
293     {
294         *(data + 3) = static_cast<uint8_t>((value >> 24) & 0xFF);
295         *(data + 2) = static_cast<uint8_t>((value >> 16) & 0xFF);
296         *(data + 1) = static_cast<uint8_t>((value >> 8) & 0xFF);
297         *data       = static_cast<uint8_t>(value & 0xFF);
298     }
299 }
300 
301 } // namespace pipe
302 } // namespace arm
303