tcmu-design.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. Contents:
  2. 1) TCM Userspace Design
  3. a) Background
  4. b) Benefits
  5. c) Design constraints
  6. d) Implementation overview
  7. i. Mailbox
  8. ii. Command ring
  9. iii. Data Area
  10. e) Device discovery
  11. f) Device events
  12. g) Other contingencies
  13. 2) Writing a user pass-through handler
  14. a) Discovering and configuring TCMU uio devices
  15. b) Waiting for events on the device(s)
  16. c) Managing the command ring
  17. 3) A final note
  18. TCM Userspace Design
  19. --------------------
  20. TCM is another name for LIO, an in-kernel iSCSI target (server).
  21. Existing TCM targets run in the kernel. TCMU (TCM in Userspace)
  22. allows userspace programs to be written which act as iSCSI targets.
  23. This document describes the design.
  24. The existing kernel provides modules for different SCSI transport
  25. protocols. TCM also modularizes the data storage. There are existing
  26. modules for file, block device, RAM or using another SCSI device as
  27. storage. These are called "backstores" or "storage engines". These
  28. built-in modules are implemented entirely as kernel code.
  29. Background:
  30. In addition to modularizing the transport protocol used for carrying
  31. SCSI commands ("fabrics"), the Linux kernel target, LIO, also modularizes
  32. the actual data storage as well. These are referred to as "backstores"
  33. or "storage engines". The target comes with backstores that allow a
  34. file, a block device, RAM, or another SCSI device to be used for the
  35. local storage needed for the exported SCSI LUN. Like the rest of LIO,
  36. these are implemented entirely as kernel code.
  37. These backstores cover the most common use cases, but not all. One new
  38. use case that other non-kernel target solutions, such as tgt, are able
  39. to support is using Gluster's GLFS or Ceph's RBD as a backstore. The
  40. target then serves as a translator, allowing initiators to store data
  41. in these non-traditional networked storage systems, while still only
  42. using standard protocols themselves.
  43. If the target is a userspace process, supporting these is easy. tgt,
  44. for example, needs only a small adapter module for each, because the
  45. modules just use the available userspace libraries for RBD and GLFS.
  46. Adding support for these backstores in LIO is considerably more
  47. difficult, because LIO is entirely kernel code. Instead of undertaking
  48. the significant work to port the GLFS or RBD APIs and protocols to the
  49. kernel, another approach is to create a userspace pass-through
  50. backstore for LIO, "TCMU".
  51. Benefits:
  52. In addition to allowing relatively easy support for RBD and GLFS, TCMU
  53. will also allow easier development of new backstores. TCMU combines
  54. with the LIO loopback fabric to become something similar to FUSE
  55. (Filesystem in Userspace), but at the SCSI layer instead of the
  56. filesystem layer. A SUSE, if you will.
  57. The disadvantage is there are more distinct components to configure, and
  58. potentially to malfunction. This is unavoidable, but hopefully not
  59. fatal if we're careful to keep things as simple as possible.
  60. Design constraints:
  61. - Good performance: high throughput, low latency
  62. - Cleanly handle if userspace:
  63. 1) never attaches
  64. 2) hangs
  65. 3) dies
  66. 4) misbehaves
  67. - Allow future flexibility in user & kernel implementations
  68. - Be reasonably memory-efficient
  69. - Simple to configure & run
  70. - Simple to write a userspace backend
  71. Implementation overview:
  72. The core of the TCMU interface is a memory region that is shared
  73. between kernel and userspace. Within this region is: a control area
  74. (mailbox); a lockless producer/consumer circular buffer for commands
  75. to be passed up, and status returned; and an in/out data buffer area.
  76. TCMU uses the pre-existing UIO subsystem. UIO allows device driver
  77. development in userspace, and this is conceptually very close to the
  78. TCMU use case, except instead of a physical device, TCMU implements a
  79. memory-mapped layout designed for SCSI commands. Using UIO also
  80. benefits TCMU by handling device introspection (e.g. a way for
  81. userspace to determine how large the shared region is) and signaling
  82. mechanisms in both directions.
  83. There are no embedded pointers in the memory region. Everything is
  84. expressed as an offset from the region's starting address. This allows
  85. the ring to still work if the user process dies and is restarted with
  86. the region mapped at a different virtual address.
  87. See target_core_user.h for the struct definitions.
  88. The Mailbox:
  89. The mailbox is always at the start of the shared memory region, and
  90. contains a version, details about the starting offset and size of the
  91. command ring, and head and tail pointers to be used by the kernel and
  92. userspace (respectively) to put commands on the ring, and indicate
  93. when the commands are completed.
  94. version - 1 (userspace should abort if otherwise)
  95. flags - none yet defined.
  96. cmdr_off - The offset of the start of the command ring from the start
  97. of the memory region, to account for the mailbox size.
  98. cmdr_size - The size of the command ring. This does *not* need to be a
  99. power of two.
  100. cmd_head - Modified by the kernel to indicate when a command has been
  101. placed on the ring.
  102. cmd_tail - Modified by userspace to indicate when it has completed
  103. processing of a command.
  104. The Command Ring:
  105. Commands are placed on the ring by the kernel incrementing
  106. mailbox.cmd_head by the size of the command, modulo cmdr_size, and
  107. then signaling userspace via uio_event_notify(). Once the command is
  108. completed, userspace updates mailbox.cmd_tail in the same way and
  109. signals the kernel via a 4-byte write(). When cmd_head equals
  110. cmd_tail, the ring is empty -- no commands are currently waiting to be
  111. processed by userspace.
  112. TCMU commands are 8-byte aligned. They start with a common header
  113. containing "len_op", a 32-bit value that stores the length, as well as
  114. the opcode in the lowest unused bits. It also contains cmd_id and
  115. flags fields for setting by the kernel (kflags) and userspace
  116. (uflags).
  117. Currently only two opcodes are defined, TCMU_OP_CMD and TCMU_OP_PAD.
  118. When the opcode is CMD, the entry in the command ring is a struct
  119. tcmu_cmd_entry. Userspace finds the SCSI CDB (Command Data Block) via
  120. tcmu_cmd_entry.req.cdb_off. This is an offset from the start of the
  121. overall shared memory region, not the entry. The data in/out buffers
  122. are accessible via tht req.iov[] array. iov_cnt contains the number of
  123. entries in iov[] needed to describe either the Data-In or Data-Out
  124. buffers. For bidirectional commands, iov_cnt specifies how many iovec
  125. entries cover the Data-Out area, and iov_bidi_cnt specifies how many
  126. iovec entries immediately after that in iov[] cover the Data-In
  127. area. Just like other fields, iov.iov_base is an offset from the start
  128. of the region.
  129. When completing a command, userspace sets rsp.scsi_status, and
  130. rsp.sense_buffer if necessary. Userspace then increments
  131. mailbox.cmd_tail by entry.hdr.length (mod cmdr_size) and signals the
  132. kernel via the UIO method, a 4-byte write to the file descriptor.
  133. When the opcode is PAD, userspace only updates cmd_tail as above --
  134. it's a no-op. (The kernel inserts PAD entries to ensure each CMD entry
  135. is contiguous within the command ring.)
  136. More opcodes may be added in the future. If userspace encounters an
  137. opcode it does not handle, it must set UNKNOWN_OP bit (bit 0) in
  138. hdr.uflags, update cmd_tail, and proceed with processing additional
  139. commands, if any.
  140. The Data Area:
  141. This is shared-memory space after the command ring. The organization
  142. of this area is not defined in the TCMU interface, and userspace
  143. should access only the parts referenced by pending iovs.
  144. Device Discovery:
  145. Other devices may be using UIO besides TCMU. Unrelated user processes
  146. may also be handling different sets of TCMU devices. TCMU userspace
  147. processes must find their devices by scanning sysfs
  148. class/uio/uio*/name. For TCMU devices, these names will be of the
  149. format:
  150. tcm-user/<hba_num>/<device_name>/<subtype>/<path>
  151. where "tcm-user" is common for all TCMU-backed UIO devices. <hba_num>
  152. and <device_name> allow userspace to find the device's path in the
  153. kernel target's configfs tree. Assuming the usual mount point, it is
  154. found at:
  155. /sys/kernel/config/target/core/user_<hba_num>/<device_name>
  156. This location contains attributes such as "hw_block_size", that
  157. userspace needs to know for correct operation.
  158. <subtype> will be a userspace-process-unique string to identify the
  159. TCMU device as expecting to be backed by a certain handler, and <path>
  160. will be an additional handler-specific string for the user process to
  161. configure the device, if needed. The name cannot contain ':', due to
  162. LIO limitations.
  163. For all devices so discovered, the user handler opens /dev/uioX and
  164. calls mmap():
  165. mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)
  166. where size must be equal to the value read from
  167. /sys/class/uio/uioX/maps/map0/size.
  168. Device Events:
  169. If a new device is added or removed, a notification will be broadcast
  170. over netlink, using a generic netlink family name of "TCM-USER" and a
  171. multicast group named "config". This will include the UIO name as
  172. described in the previous section, as well as the UIO minor
  173. number. This should allow userspace to identify both the UIO device and
  174. the LIO device, so that after determining the device is supported
  175. (based on subtype) it can take the appropriate action.
  176. Other contingencies:
  177. Userspace handler process never attaches:
  178. - TCMU will post commands, and then abort them after a timeout period
  179. (30 seconds.)
  180. Userspace handler process is killed:
  181. - It is still possible to restart and re-connect to TCMU
  182. devices. Command ring is preserved. However, after the timeout period,
  183. the kernel will abort pending tasks.
  184. Userspace handler process hangs:
  185. - The kernel will abort pending tasks after a timeout period.
  186. Userspace handler process is malicious:
  187. - The process can trivially break the handling of devices it controls,
  188. but should not be able to access kernel memory outside its shared
  189. memory areas.
  190. Writing a user pass-through handler (with example code)
  191. -------------------------------------------------------
  192. A user process handing a TCMU device must support the following:
  193. a) Discovering and configuring TCMU uio devices
  194. b) Waiting for events on the device(s)
  195. c) Managing the command ring: Parsing operations and commands,
  196. performing work as needed, setting response fields (scsi_status and
  197. possibly sense_buffer), updating cmd_tail, and notifying the kernel
  198. that work has been finished
  199. First, consider instead writing a plugin for tcmu-runner. tcmu-runner
  200. implements all of this, and provides a higher-level API for plugin
  201. authors.
  202. TCMU is designed so that multiple unrelated processes can manage TCMU
  203. devices separately. All handlers should make sure to only open their
  204. devices, based opon a known subtype string.
  205. a) Discovering and configuring TCMU UIO devices:
  206. (error checking omitted for brevity)
  207. int fd, dev_fd;
  208. char buf[256];
  209. unsigned long long map_len;
  210. void *map;
  211. fd = open("/sys/class/uio/uio0/name", O_RDONLY);
  212. ret = read(fd, buf, sizeof(buf));
  213. close(fd);
  214. buf[ret-1] = '\0'; /* null-terminate and chop off the \n */
  215. /* we only want uio devices whose name is a format we expect */
  216. if (strncmp(buf, "tcm-user", 8))
  217. exit(-1);
  218. /* Further checking for subtype also needed here */
  219. fd = open(/sys/class/uio/%s/maps/map0/size, O_RDONLY);
  220. ret = read(fd, buf, sizeof(buf));
  221. close(fd);
  222. str_buf[ret-1] = '\0'; /* null-terminate and chop off the \n */
  223. map_len = strtoull(buf, NULL, 0);
  224. dev_fd = open("/dev/uio0", O_RDWR);
  225. map = mmap(NULL, map_len, PROT_READ|PROT_WRITE, MAP_SHARED, dev_fd, 0);
  226. b) Waiting for events on the device(s)
  227. while (1) {
  228. char buf[4];
  229. int ret = read(dev_fd, buf, 4); /* will block */
  230. handle_device_events(dev_fd, map);
  231. }
  232. c) Managing the command ring
  233. #include <linux/target_core_user.h>
  234. int handle_device_events(int fd, void *map)
  235. {
  236. struct tcmu_mailbox *mb = map;
  237. struct tcmu_cmd_entry *ent = (void *) mb + mb->cmdr_off + mb->cmd_tail;
  238. int did_some_work = 0;
  239. /* Process events from cmd ring until we catch up with cmd_head */
  240. while (ent != (void *)mb + mb->cmdr_off + mb->cmd_head) {
  241. if (tcmu_hdr_get_op(ent->hdr.len_op) == TCMU_OP_CMD) {
  242. uint8_t *cdb = (void *)mb + ent->req.cdb_off;
  243. bool success = true;
  244. /* Handle command here. */
  245. printf("SCSI opcode: 0x%x\n", cdb[0]);
  246. /* Set response fields */
  247. if (success)
  248. ent->rsp.scsi_status = SCSI_NO_SENSE;
  249. else {
  250. /* Also fill in rsp->sense_buffer here */
  251. ent->rsp.scsi_status = SCSI_CHECK_CONDITION;
  252. }
  253. }
  254. else if (tcmu_hdr_get_op(ent->hdr.len_op) != TCMU_OP_PAD) {
  255. /* Tell the kernel we didn't handle unknown opcodes */
  256. ent->hdr.uflags |= TCMU_UFLAG_UNKNOWN_OP;
  257. }
  258. else {
  259. /* Do nothing for PAD entries except update cmd_tail */
  260. }
  261. /* update cmd_tail */
  262. mb->cmd_tail = (mb->cmd_tail + tcmu_hdr_get_len(&ent->hdr)) % mb->cmdr_size;
  263. ent = (void *) mb + mb->cmdr_off + mb->cmd_tail;
  264. did_some_work = 1;
  265. }
  266. /* Notify the kernel that work has been finished */
  267. if (did_some_work) {
  268. uint32_t buf = 0;
  269. write(fd, &buf, 4);
  270. }
  271. return 0;
  272. }
  273. A final note
  274. ------------
  275. Please be careful to return codes as defined by the SCSI
  276. specifications. These are different than some values defined in the
  277. scsi/scsi.h include file. For example, CHECK CONDITION's status code
  278. is 2, not 1.