Back to home page

OSCL-LXR

 
 

    


0001 .. SPDX-License-Identifier: GPL-2.0
0002 
0003 ==================================
0004 relay interface (formerly relayfs)
0005 ==================================
0006 
0007 The relay interface provides a means for kernel applications to
0008 efficiently log and transfer large quantities of data from the kernel
0009 to userspace via user-defined 'relay channels'.
0010 
0011 A 'relay channel' is a kernel->user data relay mechanism implemented
0012 as a set of per-cpu kernel buffers ('channel buffers'), each
0013 represented as a regular file ('relay file') in user space.  Kernel
0014 clients write into the channel buffers using efficient write
0015 functions; these automatically log into the current cpu's channel
0016 buffer.  User space applications mmap() or read() from the relay files
0017 and retrieve the data as it becomes available.  The relay files
0018 themselves are files created in a host filesystem, e.g. debugfs, and
0019 are associated with the channel buffers using the API described below.
0020 
0021 The format of the data logged into the channel buffers is completely
0022 up to the kernel client; the relay interface does however provide
0023 hooks which allow kernel clients to impose some structure on the
0024 buffer data.  The relay interface doesn't implement any form of data
0025 filtering - this also is left to the kernel client.  The purpose is to
0026 keep things as simple as possible.
0027 
0028 This document provides an overview of the relay interface API.  The
0029 details of the function parameters are documented along with the
0030 functions in the relay interface code - please see that for details.
0031 
0032 Semantics
0033 =========
0034 
0035 Each relay channel has one buffer per CPU, each buffer has one or more
0036 sub-buffers.  Messages are written to the first sub-buffer until it is
0037 too full to contain a new message, in which case it is written to
0038 the next (if available).  Messages are never split across sub-buffers.
0039 At this point, userspace can be notified so it empties the first
0040 sub-buffer, while the kernel continues writing to the next.
0041 
0042 When notified that a sub-buffer is full, the kernel knows how many
0043 bytes of it are padding i.e. unused space occurring because a complete
0044 message couldn't fit into a sub-buffer.  Userspace can use this
0045 knowledge to copy only valid data.
0046 
0047 After copying it, userspace can notify the kernel that a sub-buffer
0048 has been consumed.
0049 
0050 A relay channel can operate in a mode where it will overwrite data not
0051 yet collected by userspace, and not wait for it to be consumed.
0052 
0053 The relay channel itself does not provide for communication of such
0054 data between userspace and kernel, allowing the kernel side to remain
0055 simple and not impose a single interface on userspace.  It does
0056 provide a set of examples and a separate helper though, described
0057 below.
0058 
0059 The read() interface both removes padding and internally consumes the
0060 read sub-buffers; thus in cases where read(2) is being used to drain
0061 the channel buffers, special-purpose communication between kernel and
0062 user isn't necessary for basic operation.
0063 
0064 One of the major goals of the relay interface is to provide a low
0065 overhead mechanism for conveying kernel data to userspace.  While the
0066 read() interface is easy to use, it's not as efficient as the mmap()
0067 approach; the example code attempts to make the tradeoff between the
0068 two approaches as small as possible.
0069 
0070 klog and relay-apps example code
0071 ================================
0072 
0073 The relay interface itself is ready to use, but to make things easier,
0074 a couple simple utility functions and a set of examples are provided.
0075 
0076 The relay-apps example tarball, available on the relay sourceforge
0077 site, contains a set of self-contained examples, each consisting of a
0078 pair of .c files containing boilerplate code for each of the user and
0079 kernel sides of a relay application.  When combined these two sets of
0080 boilerplate code provide glue to easily stream data to disk, without
0081 having to bother with mundane housekeeping chores.
0082 
0083 The 'klog debugging functions' patch (klog.patch in the relay-apps
0084 tarball) provides a couple of high-level logging functions to the
0085 kernel which allow writing formatted text or raw data to a channel,
0086 regardless of whether a channel to write into exists or not, or even
0087 whether the relay interface is compiled into the kernel or not.  These
0088 functions allow you to put unconditional 'trace' statements anywhere
0089 in the kernel or kernel modules; only when there is a 'klog handler'
0090 registered will data actually be logged (see the klog and kleak
0091 examples for details).
0092 
0093 It is of course possible to use the relay interface from scratch,
0094 i.e. without using any of the relay-apps example code or klog, but
0095 you'll have to implement communication between userspace and kernel,
0096 allowing both to convey the state of buffers (full, empty, amount of
0097 padding).  The read() interface both removes padding and internally
0098 consumes the read sub-buffers; thus in cases where read(2) is being
0099 used to drain the channel buffers, special-purpose communication
0100 between kernel and user isn't necessary for basic operation.  Things
0101 such as buffer-full conditions would still need to be communicated via
0102 some channel though.
0103 
0104 klog and the relay-apps examples can be found in the relay-apps
0105 tarball on http://relayfs.sourceforge.net
0106 
0107 The relay interface user space API
0108 ==================================
0109 
0110 The relay interface implements basic file operations for user space
0111 access to relay channel buffer data.  Here are the file operations
0112 that are available and some comments regarding their behavior:
0113 
0114 =========== ============================================================
0115 open()      enables user to open an _existing_ channel buffer.
0116 
0117 mmap()      results in channel buffer being mapped into the caller's
0118             memory space. Note that you can't do a partial mmap - you
0119             must map the entire file, which is NRBUF * SUBBUFSIZE.
0120 
0121 read()      read the contents of a channel buffer.  The bytes read are
0122             'consumed' by the reader, i.e. they won't be available
0123             again to subsequent reads.  If the channel is being used
0124             in no-overwrite mode (the default), it can be read at any
0125             time even if there's an active kernel writer.  If the
0126             channel is being used in overwrite mode and there are
0127             active channel writers, results may be unpredictable -
0128             users should make sure that all logging to the channel has
0129             ended before using read() with overwrite mode.  Sub-buffer
0130             padding is automatically removed and will not be seen by
0131             the reader.
0132 
0133 sendfile()  transfer data from a channel buffer to an output file
0134             descriptor. Sub-buffer padding is automatically removed
0135             and will not be seen by the reader.
0136 
0137 poll()      POLLIN/POLLRDNORM/POLLERR supported.  User applications are
0138             notified when sub-buffer boundaries are crossed.
0139 
0140 close()     decrements the channel buffer's refcount.  When the refcount
0141             reaches 0, i.e. when no process or kernel client has the
0142             buffer open, the channel buffer is freed.
0143 =========== ============================================================
0144 
0145 In order for a user application to make use of relay files, the
0146 host filesystem must be mounted.  For example::
0147 
0148         mount -t debugfs debugfs /sys/kernel/debug
0149 
0150 .. Note::
0151 
0152         the host filesystem doesn't need to be mounted for kernel
0153         clients to create or use channels - it only needs to be
0154         mounted when user space applications need access to the buffer
0155         data.
0156 
0157 
0158 The relay interface kernel API
0159 ==============================
0160 
0161 Here's a summary of the API the relay interface provides to in-kernel clients:
0162 
0163 TBD(curr. line MT:/API/)
0164   channel management functions::
0165 
0166     relay_open(base_filename, parent, subbuf_size, n_subbufs,
0167                callbacks, private_data)
0168     relay_close(chan)
0169     relay_flush(chan)
0170     relay_reset(chan)
0171 
0172   channel management typically called on instigation of userspace::
0173 
0174     relay_subbufs_consumed(chan, cpu, subbufs_consumed)
0175 
0176   write functions::
0177 
0178     relay_write(chan, data, length)
0179     __relay_write(chan, data, length)
0180     relay_reserve(chan, length)
0181 
0182   callbacks::
0183 
0184     subbuf_start(buf, subbuf, prev_subbuf, prev_padding)
0185     buf_mapped(buf, filp)
0186     buf_unmapped(buf, filp)
0187     create_buf_file(filename, parent, mode, buf, is_global)
0188     remove_buf_file(dentry)
0189 
0190   helper functions::
0191 
0192     relay_buf_full(buf)
0193     subbuf_start_reserve(buf, length)
0194 
0195 
0196 Creating a channel
0197 ------------------
0198 
0199 relay_open() is used to create a channel, along with its per-cpu
0200 channel buffers.  Each channel buffer will have an associated file
0201 created for it in the host filesystem, which can be and mmapped or
0202 read from in user space.  The files are named basename0...basenameN-1
0203 where N is the number of online cpus, and by default will be created
0204 in the root of the filesystem (if the parent param is NULL).  If you
0205 want a directory structure to contain your relay files, you should
0206 create it using the host filesystem's directory creation function,
0207 e.g. debugfs_create_dir(), and pass the parent directory to
0208 relay_open().  Users are responsible for cleaning up any directory
0209 structure they create, when the channel is closed - again the host
0210 filesystem's directory removal functions should be used for that,
0211 e.g. debugfs_remove().
0212 
0213 In order for a channel to be created and the host filesystem's files
0214 associated with its channel buffers, the user must provide definitions
0215 for two callback functions, create_buf_file() and remove_buf_file().
0216 create_buf_file() is called once for each per-cpu buffer from
0217 relay_open() and allows the user to create the file which will be used
0218 to represent the corresponding channel buffer.  The callback should
0219 return the dentry of the file created to represent the channel buffer.
0220 remove_buf_file() must also be defined; it's responsible for deleting
0221 the file(s) created in create_buf_file() and is called during
0222 relay_close().
0223 
0224 Here are some typical definitions for these callbacks, in this case
0225 using debugfs::
0226 
0227     /*
0228     * create_buf_file() callback.  Creates relay file in debugfs.
0229     */
0230     static struct dentry *create_buf_file_handler(const char *filename,
0231                                                 struct dentry *parent,
0232                                                 umode_t mode,
0233                                                 struct rchan_buf *buf,
0234                                                 int *is_global)
0235     {
0236             return debugfs_create_file(filename, mode, parent, buf,
0237                                     &relay_file_operations);
0238     }
0239 
0240     /*
0241     * remove_buf_file() callback.  Removes relay file from debugfs.
0242     */
0243     static int remove_buf_file_handler(struct dentry *dentry)
0244     {
0245             debugfs_remove(dentry);
0246 
0247             return 0;
0248     }
0249 
0250     /*
0251     * relay interface callbacks
0252     */
0253     static struct rchan_callbacks relay_callbacks =
0254     {
0255             .create_buf_file = create_buf_file_handler,
0256             .remove_buf_file = remove_buf_file_handler,
0257     };
0258 
0259 And an example relay_open() invocation using them::
0260 
0261   chan = relay_open("cpu", NULL, SUBBUF_SIZE, N_SUBBUFS, &relay_callbacks, NULL);
0262 
0263 If the create_buf_file() callback fails, or isn't defined, channel
0264 creation and thus relay_open() will fail.
0265 
0266 The total size of each per-cpu buffer is calculated by multiplying the
0267 number of sub-buffers by the sub-buffer size passed into relay_open().
0268 The idea behind sub-buffers is that they're basically an extension of
0269 double-buffering to N buffers, and they also allow applications to
0270 easily implement random-access-on-buffer-boundary schemes, which can
0271 be important for some high-volume applications.  The number and size
0272 of sub-buffers is completely dependent on the application and even for
0273 the same application, different conditions will warrant different
0274 values for these parameters at different times.  Typically, the right
0275 values to use are best decided after some experimentation; in general,
0276 though, it's safe to assume that having only 1 sub-buffer is a bad
0277 idea - you're guaranteed to either overwrite data or lose events
0278 depending on the channel mode being used.
0279 
0280 The create_buf_file() implementation can also be defined in such a way
0281 as to allow the creation of a single 'global' buffer instead of the
0282 default per-cpu set.  This can be useful for applications interested
0283 mainly in seeing the relative ordering of system-wide events without
0284 the need to bother with saving explicit timestamps for the purpose of
0285 merging/sorting per-cpu files in a postprocessing step.
0286 
0287 To have relay_open() create a global buffer, the create_buf_file()
0288 implementation should set the value of the is_global outparam to a
0289 non-zero value in addition to creating the file that will be used to
0290 represent the single buffer.  In the case of a global buffer,
0291 create_buf_file() and remove_buf_file() will be called only once.  The
0292 normal channel-writing functions, e.g. relay_write(), can still be
0293 used - writes from any cpu will transparently end up in the global
0294 buffer - but since it is a global buffer, callers should make sure
0295 they use the proper locking for such a buffer, either by wrapping
0296 writes in a spinlock, or by copying a write function from relay.h and
0297 creating a local version that internally does the proper locking.
0298 
0299 The private_data passed into relay_open() allows clients to associate
0300 user-defined data with a channel, and is immediately available
0301 (including in create_buf_file()) via chan->private_data or
0302 buf->chan->private_data.
0303 
0304 Buffer-only channels
0305 --------------------
0306 
0307 These channels have no files associated and can be created with
0308 relay_open(NULL, NULL, ...). Such channels are useful in scenarios such
0309 as when doing early tracing in the kernel, before the VFS is up. In these
0310 cases, one may open a buffer-only channel and then call
0311 relay_late_setup_files() when the kernel is ready to handle files,
0312 to expose the buffered data to the userspace.
0313 
0314 Channel 'modes'
0315 ---------------
0316 
0317 relay channels can be used in either of two modes - 'overwrite' or
0318 'no-overwrite'.  The mode is entirely determined by the implementation
0319 of the subbuf_start() callback, as described below.  The default if no
0320 subbuf_start() callback is defined is 'no-overwrite' mode.  If the
0321 default mode suits your needs, and you plan to use the read()
0322 interface to retrieve channel data, you can ignore the details of this
0323 section, as it pertains mainly to mmap() implementations.
0324 
0325 In 'overwrite' mode, also known as 'flight recorder' mode, writes
0326 continuously cycle around the buffer and will never fail, but will
0327 unconditionally overwrite old data regardless of whether it's actually
0328 been consumed.  In no-overwrite mode, writes will fail, i.e. data will
0329 be lost, if the number of unconsumed sub-buffers equals the total
0330 number of sub-buffers in the channel.  It should be clear that if
0331 there is no consumer or if the consumer can't consume sub-buffers fast
0332 enough, data will be lost in either case; the only difference is
0333 whether data is lost from the beginning or the end of a buffer.
0334 
0335 As explained above, a relay channel is made of up one or more
0336 per-cpu channel buffers, each implemented as a circular buffer
0337 subdivided into one or more sub-buffers.  Messages are written into
0338 the current sub-buffer of the channel's current per-cpu buffer via the
0339 write functions described below.  Whenever a message can't fit into
0340 the current sub-buffer, because there's no room left for it, the
0341 client is notified via the subbuf_start() callback that a switch to a
0342 new sub-buffer is about to occur.  The client uses this callback to 1)
0343 initialize the next sub-buffer if appropriate 2) finalize the previous
0344 sub-buffer if appropriate and 3) return a boolean value indicating
0345 whether or not to actually move on to the next sub-buffer.
0346 
0347 To implement 'no-overwrite' mode, the userspace client would provide
0348 an implementation of the subbuf_start() callback something like the
0349 following::
0350 
0351     static int subbuf_start(struct rchan_buf *buf,
0352                             void *subbuf,
0353                             void *prev_subbuf,
0354                             unsigned int prev_padding)
0355     {
0356             if (prev_subbuf)
0357                     *((unsigned *)prev_subbuf) = prev_padding;
0358 
0359             if (relay_buf_full(buf))
0360                     return 0;
0361 
0362             subbuf_start_reserve(buf, sizeof(unsigned int));
0363 
0364             return 1;
0365     }
0366 
0367 If the current buffer is full, i.e. all sub-buffers remain unconsumed,
0368 the callback returns 0 to indicate that the buffer switch should not
0369 occur yet, i.e. until the consumer has had a chance to read the
0370 current set of ready sub-buffers.  For the relay_buf_full() function
0371 to make sense, the consumer is responsible for notifying the relay
0372 interface when sub-buffers have been consumed via
0373 relay_subbufs_consumed().  Any subsequent attempts to write into the
0374 buffer will again invoke the subbuf_start() callback with the same
0375 parameters; only when the consumer has consumed one or more of the
0376 ready sub-buffers will relay_buf_full() return 0, in which case the
0377 buffer switch can continue.
0378 
0379 The implementation of the subbuf_start() callback for 'overwrite' mode
0380 would be very similar::
0381 
0382     static int subbuf_start(struct rchan_buf *buf,
0383                             void *subbuf,
0384                             void *prev_subbuf,
0385                             size_t prev_padding)
0386     {
0387             if (prev_subbuf)
0388                     *((unsigned *)prev_subbuf) = prev_padding;
0389 
0390             subbuf_start_reserve(buf, sizeof(unsigned int));
0391 
0392             return 1;
0393     }
0394 
0395 In this case, the relay_buf_full() check is meaningless and the
0396 callback always returns 1, causing the buffer switch to occur
0397 unconditionally.  It's also meaningless for the client to use the
0398 relay_subbufs_consumed() function in this mode, as it's never
0399 consulted.
0400 
0401 The default subbuf_start() implementation, used if the client doesn't
0402 define any callbacks, or doesn't define the subbuf_start() callback,
0403 implements the simplest possible 'no-overwrite' mode, i.e. it does
0404 nothing but return 0.
0405 
0406 Header information can be reserved at the beginning of each sub-buffer
0407 by calling the subbuf_start_reserve() helper function from within the
0408 subbuf_start() callback.  This reserved area can be used to store
0409 whatever information the client wants.  In the example above, room is
0410 reserved in each sub-buffer to store the padding count for that
0411 sub-buffer.  This is filled in for the previous sub-buffer in the
0412 subbuf_start() implementation; the padding value for the previous
0413 sub-buffer is passed into the subbuf_start() callback along with a
0414 pointer to the previous sub-buffer, since the padding value isn't
0415 known until a sub-buffer is filled.  The subbuf_start() callback is
0416 also called for the first sub-buffer when the channel is opened, to
0417 give the client a chance to reserve space in it.  In this case the
0418 previous sub-buffer pointer passed into the callback will be NULL, so
0419 the client should check the value of the prev_subbuf pointer before
0420 writing into the previous sub-buffer.
0421 
0422 Writing to a channel
0423 --------------------
0424 
0425 Kernel clients write data into the current cpu's channel buffer using
0426 relay_write() or __relay_write().  relay_write() is the main logging
0427 function - it uses local_irqsave() to protect the buffer and should be
0428 used if you might be logging from interrupt context.  If you know
0429 you'll never be logging from interrupt context, you can use
0430 __relay_write(), which only disables preemption.  These functions
0431 don't return a value, so you can't determine whether or not they
0432 failed - the assumption is that you wouldn't want to check a return
0433 value in the fast logging path anyway, and that they'll always succeed
0434 unless the buffer is full and no-overwrite mode is being used, in
0435 which case you can detect a failed write in the subbuf_start()
0436 callback by calling the relay_buf_full() helper function.
0437 
0438 relay_reserve() is used to reserve a slot in a channel buffer which
0439 can be written to later.  This would typically be used in applications
0440 that need to write directly into a channel buffer without having to
0441 stage data in a temporary buffer beforehand.  Because the actual write
0442 may not happen immediately after the slot is reserved, applications
0443 using relay_reserve() can keep a count of the number of bytes actually
0444 written, either in space reserved in the sub-buffers themselves or as
0445 a separate array.  See the 'reserve' example in the relay-apps tarball
0446 at http://relayfs.sourceforge.net for an example of how this can be
0447 done.  Because the write is under control of the client and is
0448 separated from the reserve, relay_reserve() doesn't protect the buffer
0449 at all - it's up to the client to provide the appropriate
0450 synchronization when using relay_reserve().
0451 
0452 Closing a channel
0453 -----------------
0454 
0455 The client calls relay_close() when it's finished using the channel.
0456 The channel and its associated buffers are destroyed when there are no
0457 longer any references to any of the channel buffers.  relay_flush()
0458 forces a sub-buffer switch on all the channel buffers, and can be used
0459 to finalize and process the last sub-buffers before the channel is
0460 closed.
0461 
0462 Misc
0463 ----
0464 
0465 Some applications may want to keep a channel around and re-use it
0466 rather than open and close a new channel for each use.  relay_reset()
0467 can be used for this purpose - it resets a channel to its initial
0468 state without reallocating channel buffer memory or destroying
0469 existing mappings.  It should however only be called when it's safe to
0470 do so, i.e. when the channel isn't currently being written to.
0471 
0472 Finally, there are a couple of utility callbacks that can be used for
0473 different purposes.  buf_mapped() is called whenever a channel buffer
0474 is mmapped from user space and buf_unmapped() is called when it's
0475 unmapped.  The client can use this notification to trigger actions
0476 within the kernel application, such as enabling/disabling logging to
0477 the channel.
0478 
0479 
0480 Resources
0481 =========
0482 
0483 For news, example code, mailing list, etc. see the relay interface homepage:
0484 
0485     http://relayfs.sourceforge.net
0486 
0487 
0488 Credits
0489 =======
0490 
0491 The ideas and specs for the relay interface came about as a result of
0492 discussions on tracing involving the following:
0493 
0494 Michel Dagenais         <michel.dagenais@polymtl.ca>
0495 Richard Moore           <richardj_moore@uk.ibm.com>
0496 Bob Wisniewski          <bob@watson.ibm.com>
0497 Karim Yaghmour          <karim@opersys.com>
0498 Tom Zanussi             <zanussi@us.ibm.com>
0499 
0500 Also thanks to Hubertus Franke for a lot of useful suggestions and bug
0501 reports.