gem5  v22.0.0.2
shared_memory_server.cc
Go to the documentation of this file.
1 /*
2  * Copyright 2022 Google, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met: redistributions of source code must retain the above copyright
7  * notice, this list of conditions and the following disclaimer;
8  * redistributions in binary form must reproduce the above copyright
9  * notice, this list of conditions and the following disclaimer in the
10  * documentation and/or other materials provided with the distribution;
11  * neither the name of the copyright holders nor the names of its
12  * contributors may be used to endorse or promote products derived from
13  * this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
29 
30 #include <arpa/inet.h>
31 #include <fcntl.h>
32 #include <poll.h>
33 #include <sys/mman.h>
34 #include <sys/socket.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <sys/un.h>
38 #include <unistd.h>
39 
40 #include <algorithm>
41 #include <cerrno>
42 #include <cstring>
43 
44 #include "base/logging.hh"
45 #include "base/output.hh"
46 #include "base/pollevent.hh"
47 #include "base/socket.hh"
48 
49 namespace gem5
50 {
51 namespace memory
52 {
53 
54 SharedMemoryServer::SharedMemoryServer(const SharedMemoryServerParams& params)
55  : SimObject(params), unixSocketPath(simout.resolve(params.server_path)),
56  system(params.system), serverFd(-1)
57 {
58  fatal_if(system == nullptr, "Requires a system to share memory from!");
59  // Ensure the unix socket path to use is not occupied. Also, if there's
60  // actually anything to be removed, warn the user something might be off.
61  if (unlink(unixSocketPath.c_str()) == 0) {
62  warn(
63  "The server path %s was occupied and will be replaced. Please "
64  "make sure there is no other server using the same path.",
65  unixSocketPath.c_str());
66  }
67  // Create a new unix socket.
68  serverFd = ListenSocket::socketCloexec(AF_UNIX, SOCK_STREAM, 0);
69  panic_if(serverFd < 0, "%s: cannot create unix socket: %s", name().c_str(),
70  strerror(errno));
71  // Bind to the specified path.
72  sockaddr_un serv_addr = {};
73  serv_addr.sun_family = AF_UNIX;
74  strncpy(serv_addr.sun_path, unixSocketPath.c_str(),
75  sizeof(serv_addr.sun_path) - 1);
76  warn_if(strlen(serv_addr.sun_path) != unixSocketPath.size(),
77  "%s: unix socket path truncated, expect '%s' but get '%s'",
78  name().c_str(), unixSocketPath.c_str(), serv_addr.sun_path);
79  int bind_retv = bind(serverFd, reinterpret_cast<sockaddr*>(&serv_addr),
80  sizeof(serv_addr));
81  fatal_if(bind_retv != 0, "%s: cannot bind unix socket: %s", name().c_str(),
82  strerror(errno));
83  // Start listening.
84  int listen_retv = listen(serverFd, 1);
85  fatal_if(listen_retv != 0, "%s: listen failed: %s", name().c_str(),
86  strerror(errno));
89  inform("%s: listening at %s", name().c_str(), unixSocketPath.c_str());
90 }
91 
93 {
94  int unlink_retv = unlink(unixSocketPath.c_str());
95  warn_if(unlink_retv != 0, "%s: cannot unlink unix socket: %s",
96  name().c_str(), strerror(errno));
97  int close_retv = close(serverFd);
98  warn_if(close_retv != 0, "%s: cannot close unix socket: %s",
99  name().c_str(), strerror(errno));
100 }
101 
103  int fd, SharedMemoryServer* shm_server)
104  : PollEvent(fd, POLLIN), shmServer(shm_server),
105  eventName(shmServer->name() + ".fd" + std::to_string(fd))
106 {
107 }
108 
109 const std::string&
111 {
112  return eventName;
113 }
114 
115 bool
117 {
118  char* char_buffer = reinterpret_cast<char*>(buffer);
119  for (size_t offset = 0; offset < size;) {
120  ssize_t retv = recv(pfd.fd, char_buffer + offset, size - offset, 0);
121  if (retv >= 0) {
122  offset += retv;
123  } else if (errno != EINTR) {
124  warn("%s: recv failed: %s", name().c_str(), strerror(errno));
125  return false;
126  }
127  }
128  return true;
129 }
130 
131 void
133 {
134  panic_if(revents & (POLLERR | POLLNVAL), "%s: listen socket is broken",
135  name().c_str());
136  int cli_fd = ListenSocket::acceptCloexec(pfd.fd, nullptr, nullptr);
137  panic_if(cli_fd < 0, "%s: accept failed: %s", name().c_str(),
138  strerror(errno));
139  panic_if(shmServer->clientSocketEvent.get(),
140  "%s: cannot serve two clients at once", name().c_str());
141  inform("%s: accept new connection %d", name().c_str(), cli_fd);
142  shmServer->clientSocketEvent.reset(
143  new ClientSocketEvent(cli_fd, shmServer));
144  pollQueue.schedule(shmServer->clientSocketEvent.get());
145 }
146 
147 void
149 {
150  do {
151  // Ensure the connection is not closed nor broken.
152  if (revents & (POLLHUP | POLLERR | POLLNVAL)) {
153  break;
154  }
155 
156  // Receive a request packet. We ignore the endianness as unix socket
157  // only allows communication on the same system anyway.
158  RequestType req_type;
159  struct
160  {
161  uint64_t start;
162  uint64_t end;
163  } request;
164  if (!tryReadAll(&req_type, sizeof(req_type))) {
165  break;
166  }
167  if (req_type != RequestType::kGetPhysRange) {
168  warn("%s: receive unknown request: %d", name().c_str(),
169  static_cast<int>(req_type));
170  break;
171  }
172  if (!tryReadAll(&request, sizeof(request))) {
173  break;
174  }
175  AddrRange range(request.start, request.end);
176  inform("%s: receive request: %s", name().c_str(),
177  range.to_string().c_str());
178 
179  // Identify the backing store.
180  const auto& stores = shmServer->system->getPhysMem().getBackingStore();
181  auto it = std::find_if(
182  stores.begin(), stores.end(), [&](const BackingStoreEntry& entry) {
183  return entry.shmFd >= 0 && range.isSubset(entry.range);
184  });
185  if (it == stores.end()) {
186  warn("%s: cannot find backing store for %s", name().c_str(),
187  range.to_string().c_str());
188  break;
189  }
190  inform("%s: find shared backing store for %s at %s, shm=%d:%lld",
191  name().c_str(), range.to_string().c_str(),
192  it->range.to_string().c_str(), it->shmFd,
193  (unsigned long long)it->shmOffset);
194 
195  // Populate response message.
196  // mmap fd @ offset <===> [start, end] in simulated phys mem.
197  msghdr msg = {};
198  // Setup iovec for fields other than fd. We ignore the endianness as
199  // unix socket only allows communication on the same system anyway.
200  struct
201  {
202  off_t offset;
203  } response;
204  // (offset of the request range in shared memory) =
205  // (offset of the full range in shared memory) +
206  // (offset of the request range in the full range)
207  response.offset = it->shmOffset + (range.start() - it->range.start());
208  iovec ios = {.iov_base = &response, .iov_len = sizeof(response)};
209  msg.msg_iov = &ios;
210  msg.msg_iovlen = 1;
211  // Setup fd as an ancillary data.
212  union
213  {
214  char buf[CMSG_SPACE(sizeof(it->shmFd))];
215  struct cmsghdr align;
216  } cmsgs;
217  msg.msg_control = cmsgs.buf;
218  msg.msg_controllen = sizeof(cmsgs.buf);
219  cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
220  cmsg->cmsg_level = SOL_SOCKET;
221  cmsg->cmsg_type = SCM_RIGHTS;
222  cmsg->cmsg_len = CMSG_LEN(sizeof(it->shmFd));
223  memcpy(CMSG_DATA(cmsg), &it->shmFd, sizeof(it->shmFd));
224  // Send the response.
225  int retv = sendmsg(pfd.fd, &msg, 0);
226  if (retv < 0) {
227  warn("%s: sendmsg failed: %s", name().c_str(), strerror(errno));
228  break;
229  }
230  if (retv != sizeof(response)) {
231  warn("%s: failed to send all response at once", name().c_str());
232  break;
233  }
234 
235  // Request done.
236  inform("%s: request done", name().c_str());
237  return;
238  } while (false);
239 
240  // If we ever reach here, our client either close the connection or is
241  // somehow broken. We'll just close the connection and move on.
242  inform("%s: closing connection", name().c_str());
243  close(pfd.fd);
244  shmServer->clientSocketEvent.reset();
245 }
246 
247 } // namespace memory
248 } // namespace gem5
gem5::memory::SharedMemoryServer::RequestType
RequestType
Definition: shared_memory_server.hh:47
gem5::AddrRange::to_string
std::string to_string() const
Get a string representation of the range.
Definition: addr_range.hh:360
socket.hh
gem5::AddrRange::start
Addr start() const
Get the start address of the range.
Definition: addr_range.hh:343
warn
#define warn(...)
Definition: logging.hh:246
gem5::ArmISA::fd
Bitfield< 14, 12 > fd
Definition: types.hh:150
gem5::memory::SharedMemoryServer::RequestType::kGetPhysRange
@ kGetPhysRange
memory
Definition: mem.h:38
gem5::statistics::resolve
const Info * resolve(const std::string &name)
Definition: statistics.cc:319
gem5::pollQueue
PollQueue pollQueue
Definition: pollevent.cc:55
gem5::memory::SharedMemoryServer::system
System * system
Definition: shared_memory_server.hh:85
sc_dt::to_string
const std::string to_string(sc_enc enc)
Definition: sc_fxdefs.cc:91
gem5::simout
OutputDirectory simout
Definition: output.cc:62
gem5::X86ISA::system
Bitfield< 15 > system
Definition: misc.hh:997
gem5::memory::SharedMemoryServer::ClientSocketEvent
Definition: shared_memory_server.hh:77
gem5::PollEvent
Definition: pollevent.hh:43
output.hh
sc_dt::align
void align(const scfx_rep &lhs, const scfx_rep &rhs, int &new_wp, int &len_mant, scfx_mant_ref &lhs_mant, scfx_mant_ref &rhs_mant)
Definition: scfx_rep.cc:2083
gem5::memory::SharedMemoryServer::serverFd
int serverFd
Definition: shared_memory_server.hh:87
gem5::memory::SharedMemoryServer::BaseShmPollEvent::tryReadAll
bool tryReadAll(void *buffer, size_t size)
Definition: shared_memory_server.cc:116
gem5::memory::SharedMemoryServer::~SharedMemoryServer
~SharedMemoryServer()
Definition: shared_memory_server.cc:92
gem5::Named::name
virtual std::string name() const
Definition: named.hh:47
gem5::ListenSocket::acceptCloexec
static int acceptCloexec(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
Definition: socket.cc:96
gem5::memory::BackingStoreEntry
A single entry for the backing store.
Definition: physical.hh:64
pollevent.hh
gem5::memory::SharedMemoryServer::SharedMemoryServer
SharedMemoryServer(const SharedMemoryServerParams &params)
Definition: shared_memory_server.cc:54
gem5::ArmISA::offset
Bitfield< 23, 0 > offset
Definition: types.hh:144
gem5::memory::SharedMemoryServer::ListenSocketEvent::process
void process(int revent) override
Definition: shared_memory_server.cc:132
gem5::PollQueue::schedule
void schedule(PollEvent *event)
Definition: pollevent.cc:159
gem5::SimObject
Abstract superclass for simulation objects.
Definition: sim_object.hh:146
name
const std::string & name()
Definition: trace.cc:49
gem5::memory::SharedMemoryServer::ClientSocketEvent::process
void process(int revent) override
Definition: shared_memory_server.cc:148
gem5::memory::SharedMemoryServer::BaseShmPollEvent::BaseShmPollEvent
BaseShmPollEvent(int fd, SharedMemoryServer *shm_server)
Definition: shared_memory_server.cc:102
warn_if
#define warn_if(cond,...)
Conditional warning macro that checks the supplied condition and only prints a warning if the conditi...
Definition: logging.hh:273
panic_if
#define panic_if(cond,...)
Conditional panic macro that checks the supplied condition and only panics if the condition is true a...
Definition: logging.hh:204
shared_memory_server.hh
inform
#define inform(...)
Definition: logging.hh:247
std
Overload hash function for BasicBlockRange type.
Definition: misc.hh:2388
gem5::ListenSocket::socketCloexec
static int socketCloexec(int domain, int type, int protocol)
Definition: socket.cc:87
gem5::memory::SharedMemoryServer::ListenSocketEvent
Definition: shared_memory_server.hh:70
logging.hh
gem5::AddrRange
The AddrRange class encapsulates an address range, and supports a number of tests to check if two ran...
Definition: addr_range.hh:81
gem5::memory::SharedMemoryServer::listenSocketEvent
std::unique_ptr< ListenSocketEvent > listenSocketEvent
Definition: shared_memory_server.hh:88
gem5::memory::SharedMemoryServer
Definition: shared_memory_server.hh:44
fatal_if
#define fatal_if(cond,...)
Conditional fatal macro that checks the supplied condition and only causes a fatal error if the condi...
Definition: logging.hh:226
gem5
Reference material can be found at the JEDEC website: UFS standard http://www.jedec....
Definition: gpu_translation_state.hh:37
gem5::memory::SharedMemoryServer::BaseShmPollEvent::name
const std::string & name() const
Definition: shared_memory_server.cc:110
gem5::memory::SharedMemoryServer::unixSocketPath
std::string unixSocketPath
Definition: shared_memory_server.hh:84

Generated on Thu Jul 28 2022 13:32:36 for gem5 by doxygen 1.8.17