netlink_mmap.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. This file documents how to use memory mapped I/O with netlink.
  2. Author: Patrick McHardy <kaber@trash.net>
  3. Overview
  4. --------
  5. Memory mapped netlink I/O can be used to increase throughput and decrease
  6. overhead of unicast receive and transmit operations. Some netlink subsystems
  7. require high throughput, these are mainly the netfilter subsystems
  8. nfnetlink_queue and nfnetlink_log, but it can also help speed up large
  9. dump operations of f.i. the routing database.
  10. Memory mapped netlink I/O used two circular ring buffers for RX and TX which
  11. are mapped into the processes address space.
  12. The RX ring is used by the kernel to directly construct netlink messages into
  13. user-space memory without copying them as done with regular socket I/O,
  14. additionally as long as the ring contains messages no recvmsg() or poll()
  15. syscalls have to be issued by user-space to get more message.
  16. The TX ring is used to process messages directly from user-space memory, the
  17. kernel processes all messages contained in the ring using a single sendmsg()
  18. call.
  19. Usage overview
  20. --------------
  21. In order to use memory mapped netlink I/O, user-space needs three main changes:
  22. - ring setup
  23. - conversion of the RX path to get messages from the ring instead of recvmsg()
  24. - conversion of the TX path to construct messages into the ring
  25. Ring setup is done using setsockopt() to provide the ring parameters to the
  26. kernel, then a call to mmap() to map the ring into the processes address space:
  27. - setsockopt(fd, SOL_NETLINK, NETLINK_RX_RING, &params, sizeof(params));
  28. - setsockopt(fd, SOL_NETLINK, NETLINK_TX_RING, &params, sizeof(params));
  29. - ring = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)
  30. Usage of either ring is optional, but even if only the RX ring is used the
  31. mapping still needs to be writable in order to update the frame status after
  32. processing.
  33. Conversion of the reception path involves calling poll() on the file
  34. descriptor, once the socket is readable the frames from the ring are
  35. processsed in order until no more messages are available, as indicated by
  36. a status word in the frame header.
  37. On kernel side, in order to make use of memory mapped I/O on receive, the
  38. originating netlink subsystem needs to support memory mapped I/O, otherwise
  39. it will use an allocated socket buffer as usual and the contents will be
  40. copied to the ring on transmission, nullifying most of the performance gains.
  41. Dumps of kernel databases automatically support memory mapped I/O.
  42. Conversion of the transmit path involves changing message construction to
  43. use memory from the TX ring instead of (usually) a buffer declared on the
  44. stack and setting up the frame header approriately. Optionally poll() can
  45. be used to wait for free frames in the TX ring.
  46. Structured and definitions for using memory mapped I/O are contained in
  47. <linux/netlink.h>.
  48. RX and TX rings
  49. ----------------
  50. Each ring contains a number of continuous memory blocks, containing frames of
  51. fixed size dependent on the parameters used for ring setup.
  52. Ring: [ block 0 ]
  53. [ frame 0 ]
  54. [ frame 1 ]
  55. [ block 1 ]
  56. [ frame 2 ]
  57. [ frame 3 ]
  58. ...
  59. [ block n ]
  60. [ frame 2 * n ]
  61. [ frame 2 * n + 1 ]
  62. The blocks are only visible to the kernel, from the point of view of user-space
  63. the ring just contains the frames in a continuous memory zone.
  64. The ring parameters used for setting up the ring are defined as follows:
  65. struct nl_mmap_req {
  66. unsigned int nm_block_size;
  67. unsigned int nm_block_nr;
  68. unsigned int nm_frame_size;
  69. unsigned int nm_frame_nr;
  70. };
  71. Frames are grouped into blocks, where each block is a continuous region of memory
  72. and holds nm_block_size / nm_frame_size frames. The total number of frames in
  73. the ring is nm_frame_nr. The following invariants hold:
  74. - frames_per_block = nm_block_size / nm_frame_size
  75. - nm_frame_nr = frames_per_block * nm_block_nr
  76. Some parameters are constrained, specifically:
  77. - nm_block_size must be a multiple of the architectures memory page size.
  78. The getpagesize() function can be used to get the page size.
  79. - nm_frame_size must be equal or larger to NL_MMAP_HDRLEN, IOW a frame must be
  80. able to hold at least the frame header
  81. - nm_frame_size must be smaller or equal to nm_block_size
  82. - nm_frame_size must be a multiple of NL_MMAP_MSG_ALIGNMENT
  83. - nm_frame_nr must equal the actual number of frames as specified above.
  84. When the kernel can't allocate physically continuous memory for a ring block,
  85. it will fall back to use physically discontinuous memory. This might affect
  86. performance negatively, in order to avoid this the nm_frame_size parameter
  87. should be chosen to be as small as possible for the required frame size and
  88. the number of blocks should be increased instead.
  89. Ring frames
  90. ------------
  91. Each frames contain a frame header, consisting of a synchronization word and some
  92. meta-data, and the message itself.
  93. Frame: [ header message ]
  94. The frame header is defined as follows:
  95. struct nl_mmap_hdr {
  96. unsigned int nm_status;
  97. unsigned int nm_len;
  98. __u32 nm_group;
  99. /* credentials */
  100. __u32 nm_pid;
  101. __u32 nm_uid;
  102. __u32 nm_gid;
  103. };
  104. - nm_status is used for synchronizing processing between the kernel and user-
  105. space and specifies ownership of the frame as well as the operation to perform
  106. - nm_len contains the length of the message contained in the data area
  107. - nm_group specified the destination multicast group of message
  108. - nm_pid, nm_uid and nm_gid contain the netlink pid, UID and GID of the sending
  109. process. These values correspond to the data available using SOCK_PASSCRED in
  110. the SCM_CREDENTIALS cmsg.
  111. The possible values in the status word are:
  112. - NL_MMAP_STATUS_UNUSED:
  113. RX ring: frame belongs to the kernel and contains no message
  114. for user-space. Approriate action is to invoke poll()
  115. to wait for new messages.
  116. TX ring: frame belongs to user-space and can be used for
  117. message construction.
  118. - NL_MMAP_STATUS_RESERVED:
  119. RX ring only: frame is currently used by the kernel for message
  120. construction and contains no valid message yet.
  121. Appropriate action is to invoke poll() to wait for
  122. new messages.
  123. - NL_MMAP_STATUS_VALID:
  124. RX ring: frame contains a valid message. Approriate action is
  125. to process the message and release the frame back to
  126. the kernel by setting the status to
  127. NL_MMAP_STATUS_UNUSED or queue the frame by setting the
  128. status to NL_MMAP_STATUS_SKIP.
  129. TX ring: the frame contains a valid message from user-space to
  130. be processed by the kernel. After completing processing
  131. the kernel will release the frame back to user-space by
  132. setting the status to NL_MMAP_STATUS_UNUSED.
  133. - NL_MMAP_STATUS_COPY:
  134. RX ring only: a message is ready to be processed but could not be
  135. stored in the ring, either because it exceeded the
  136. frame size or because the originating subsystem does
  137. not support memory mapped I/O. Appropriate action is
  138. to invoke recvmsg() to receive the message and release
  139. the frame back to the kernel by setting the status to
  140. NL_MMAP_STATUS_UNUSED.
  141. - NL_MMAP_STATUS_SKIP:
  142. RX ring only: user-space queued the message for later processing, but
  143. processed some messages following it in the ring. The
  144. kernel should skip this frame when looking for unused
  145. frames.
  146. The data area of a frame begins at a offset of NL_MMAP_HDRLEN relative to the
  147. frame header.
  148. TX limitations
  149. --------------
  150. Kernel processing usually involves validation of the message received by
  151. user-space, then processing its contents. The kernel must assure that
  152. userspace is not able to modify the message contents after they have been
  153. validated. In order to do so, the message is copied from the ring frame
  154. to an allocated buffer if either of these conditions is false:
  155. - only a single mapping of the ring exists
  156. - the file descriptor is not shared between processes
  157. This means that for threaded programs, the kernel will fall back to copying.
  158. Example
  159. -------
  160. Ring setup:
  161. unsigned int block_size = 16 * getpagesize();
  162. struct nl_mmap_req req = {
  163. .nm_block_size = block_size,
  164. .nm_block_nr = 64,
  165. .nm_frame_size = 16384,
  166. .nm_frame_nr = 64 * block_size / 16384,
  167. };
  168. unsigned int ring_size;
  169. void *rx_ring, *tx_ring;
  170. /* Configure ring parameters */
  171. if (setsockopt(fd, NETLINK_RX_RING, &req, sizeof(req)) < 0)
  172. exit(1);
  173. if (setsockopt(fd, NETLINK_TX_RING, &req, sizeof(req)) < 0)
  174. exit(1)
  175. /* Calculate size of each invididual ring */
  176. ring_size = req.nm_block_nr * req.nm_block_size;
  177. /* Map RX/TX rings. The TX ring is located after the RX ring */
  178. rx_ring = mmap(NULL, 2 * ring_size, PROT_READ | PROT_WRITE,
  179. MAP_SHARED, fd, 0);
  180. if ((long)rx_ring == -1L)
  181. exit(1);
  182. tx_ring = rx_ring + ring_size:
  183. Message reception:
  184. This example assumes some ring parameters of the ring setup are available.
  185. unsigned int frame_offset = 0;
  186. struct nl_mmap_hdr *hdr;
  187. struct nlmsghdr *nlh;
  188. unsigned char buf[16384];
  189. ssize_t len;
  190. while (1) {
  191. struct pollfd pfds[1];
  192. pfds[0].fd = fd;
  193. pfds[0].events = POLLIN | POLLERR;
  194. pfds[0].revents = 0;
  195. if (poll(pfds, 1, -1) < 0 && errno != -EINTR)
  196. exit(1);
  197. /* Check for errors. Error handling omitted */
  198. if (pfds[0].revents & POLLERR)
  199. <handle error>
  200. /* If no new messages, poll again */
  201. if (!(pfds[0].revents & POLLIN))
  202. continue;
  203. /* Process all frames */
  204. while (1) {
  205. /* Get next frame header */
  206. hdr = rx_ring + frame_offset;
  207. if (hdr->nm_status == NL_MMAP_STATUS_VALID) {
  208. /* Regular memory mapped frame */
  209. nlh = (void *)hdr + NL_MMAP_HDRLEN;
  210. len = hdr->nm_len;
  211. /* Release empty message immediately. May happen
  212. * on error during message construction.
  213. */
  214. if (len == 0)
  215. goto release;
  216. } else if (hdr->nm_status == NL_MMAP_STATUS_COPY) {
  217. /* Frame queued to socket receive queue */
  218. len = recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
  219. if (len <= 0)
  220. break;
  221. nlh = buf;
  222. } else
  223. /* No more messages to process, continue polling */
  224. break;
  225. process_msg(nlh);
  226. release:
  227. /* Release frame back to the kernel */
  228. hdr->nm_status = NL_MMAP_STATUS_UNUSED;
  229. /* Advance frame offset to next frame */
  230. frame_offset = (frame_offset + frame_size) % ring_size;
  231. }
  232. }
  233. Message transmission:
  234. This example assumes some ring parameters of the ring setup are available.
  235. A single message is constructed and transmitted, to send multiple messages
  236. at once they would be constructed in consecutive frames before a final call
  237. to sendto().
  238. unsigned int frame_offset = 0;
  239. struct nl_mmap_hdr *hdr;
  240. struct nlmsghdr *nlh;
  241. struct sockaddr_nl addr = {
  242. .nl_family = AF_NETLINK,
  243. };
  244. hdr = tx_ring + frame_offset;
  245. if (hdr->nm_status != NL_MMAP_STATUS_UNUSED)
  246. /* No frame available. Use poll() to avoid. */
  247. exit(1);
  248. nlh = (void *)hdr + NL_MMAP_HDRLEN;
  249. /* Build message */
  250. build_message(nlh);
  251. /* Fill frame header: length and status need to be set */
  252. hdr->nm_len = nlh->nlmsg_len;
  253. hdr->nm_status = NL_MMAP_STATUS_VALID;
  254. if (sendto(fd, NULL, 0, 0, &addr, sizeof(addr)) < 0)
  255. exit(1);
  256. /* Advance frame offset to next frame */
  257. frame_offset = (frame_offset + frame_size) % ring_size;