logring.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /*
  2. *
  3. * Copyright (c) 2003 The Regents of the University of California. All
  4. * rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * - Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. *
  13. * - Neither the name of the University nor the names of its
  14. * contributors may be used to endorse or promote products derived
  15. * from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
  18. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  19. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  20. * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
  21. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  22. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  23. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  24. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  25. * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. */
  30. /*
  31. * FUSD - The Framework for UserSpace Devices - Example program
  32. *
  33. * Jeremy Elson <jelson@circlemud.org>
  34. *
  35. * logring.c: Implementation of a circular buffer log device
  36. *
  37. * logring makes it easy to access the most recent (and only the most
  38. * recent) output from a process. It works just like "tail -f" on a
  39. * log file, except that the storage required never grows. This can be
  40. * useful in embedded systems where there isn't enough memory or disk
  41. * space for keeping complete log files, but the most recent debugging
  42. * messages are sometimes needed (e.g., after an error is observed).
  43. *
  44. * Logring uses FUSD to implement a character device, /dev/logring,
  45. * that acts like a named pipe that has a finite, circular buffer.
  46. * The size of the buffer is given as a command-line argument. As
  47. * more data is written into the buffer, the oldest data is discarded.
  48. * A process that reads from the logring device will first read the
  49. * existing buffer, then block and see new data as it's written,
  50. * similar to monitoring a log file using "tail -f".
  51. *
  52. * Non-blocking reads are supported; if a process needs to get the
  53. * current contents of the log without blocking to wait for new data,
  54. * it can set the O_NONBLOCK flag when it does the open(), or set it
  55. * later using ioctl().
  56. *
  57. * The select() interface is also supported; programs can select on
  58. * /dev/logring to be notified when new data is available.
  59. *
  60. * Run this example program by typing "logring X", where X is the size
  61. * of the circular buffer in bytes. Then, type "cat /dev/logring" in
  62. * one shell. The cat process will block, waiting for data, similar
  63. * to "tail -f". From another shell, write to the logring (e.g.,
  64. * "echo Hi there > /dev/logring".) The 'cat' process will see the
  65. * message appear.
  66. *
  67. * Note: this example program is based on "emlog", a true Linux kernel
  68. * module with identical functionality. If you find logring useful,
  69. * but want to use it on a system that does not have FUSD, check out
  70. * emlog at http://www.circlemud.org/~jelson/software/emlog.
  71. *
  72. */
  73. #include <stdio.h>
  74. #include <stdlib.h>
  75. #include <string.h>
  76. #include <errno.h>
  77. #include <fcntl.h>
  78. #include <fusd.h>
  79. /* per-client structure to keep track of who has an open FD to us */
  80. struct logring_client {
  81. /* used to store outstanding read and polldiff requests */
  82. struct fusd_file_info *read;
  83. struct fusd_file_info *polldiff;
  84. /* to construct the linked list */
  85. struct logring_client *next;
  86. };
  87. /* list of currently open file descriptors */
  88. struct logring_client *client_list = NULL;
  89. char *logring_data = NULL; /* the data buffer used for the logring */
  90. int logring_size = 0; /* buffer space in the logring */
  91. int logring_writeindex = 0; /* write point in the logring array */
  92. int logring_readindex = 0; /* read point in the logring array */
  93. int logring_offset = 0; /* how far into the total stream is
  94. * logring_read pointing? */
  95. /* amount of data in the queue */
  96. #define LOGRING_QLEN (logring_writeindex >= logring_readindex ? \
  97. logring_writeindex - logring_readindex : \
  98. logring_size - logring_readindex + logring_writeindex)
  99. /* stream byte number of the last byte in the queue */
  100. #define LOGRING_FIRST_EMPTY_BYTE (logring_offset + LOGRING_QLEN)
  101. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  102. /************************************************************************/
  103. /*
  104. * this function removes an element from a linked list. the
  105. * pointer-manipulation insanity below is a trick that prevents the
  106. * "element to be removed is the head of the list" from being a
  107. * special case.
  108. */
  109. void client_list_remove(struct logring_client *c)
  110. {
  111. struct logring_client **ptr;
  112. if (c == NULL || client_list == NULL)
  113. return;
  114. for (ptr = &client_list; *ptr != c; ptr = &((**ptr).next)) {
  115. if (!*ptr) {
  116. fprintf(stderr, "trying to remove a client that isn't in the list\n");
  117. return;
  118. }
  119. }
  120. *ptr = c->next;
  121. }
  122. /* open on /dev/logring: create state for this client */
  123. static int logring_open(struct fusd_file_info *file)
  124. {
  125. /* create state for this client */
  126. struct logring_client *c = malloc(sizeof(struct logring_client));
  127. if (c == NULL)
  128. return -ENOBUFS;
  129. /* initialize fields of this client state */
  130. memset(c, 0, sizeof(struct logring_client));
  131. /* save the pointer to this state so it gets returned to us later */
  132. file->private_data = c;
  133. /* add this client to the client list */
  134. c->next = client_list;
  135. client_list = c;
  136. return 0;
  137. }
  138. /* close on /dev/logring: destroy state for this client */
  139. static int logring_close(struct fusd_file_info *file)
  140. {
  141. struct logring_client *c;
  142. if ((c = (struct logring_client *) file->private_data) != NULL) {
  143. /* take this client off our client list */
  144. client_list_remove(c);
  145. /* if there is a read outstanding, free the state */
  146. if (c->read != NULL) {
  147. fusd_destroy(c->read);
  148. c->read = NULL;
  149. }
  150. /* destroy any outstanding polldiffs */
  151. if (c->polldiff != NULL) {
  152. fusd_destroy(c->polldiff);
  153. c->polldiff = NULL;
  154. }
  155. /* get rid of the struct */
  156. free(c);
  157. file->private_data = NULL;
  158. }
  159. return 0;
  160. }
  161. /*
  162. * This function "completes" a read: that is, matches up a client who
  163. * is requesting data with data that's waiting to be served.
  164. *
  165. * This function is called in two cases:
  166. *
  167. * 1- When a new read request comes in (it might be able to complete
  168. * immediately, if there's data waiting that the client hasn't seen
  169. * yet)
  170. *
  171. * 2- When new data comes in (the new data might be able to complete
  172. * a read that had been previously blocked)
  173. */
  174. void logring_complete_read(struct logring_client *c)
  175. {
  176. loff_t *user_offset;
  177. char *user_buffer;
  178. size_t user_length;
  179. int bytes_copied = 0, n, start_point, retval;
  180. /* if there is no outstanding read, do nothing */
  181. if (c == NULL || c->read == NULL)
  182. return;
  183. /* retrieve the read callback's arguments */
  184. user_offset = fusd_get_offset(c->read);
  185. user_buffer = fusd_get_read_buffer(c->read);
  186. user_length = fusd_get_length(c->read);
  187. /* is the client trying to read data that has scrolled off? */
  188. if (*user_offset < logring_offset)
  189. *user_offset = logring_offset;
  190. /* is there new data this user hasn't seen yet, or are we at EOF? */
  191. /* If we have reached EOF:
  192. * If this is a nonblocking read, return EAGAIN.
  193. * else return without doing anything; keep the read blocked.
  194. */
  195. if (*user_offset >= LOGRING_FIRST_EMPTY_BYTE) {
  196. if (c->read->flags & O_NONBLOCK) {
  197. retval = -EAGAIN;
  198. goto done;
  199. } else {
  200. return;
  201. }
  202. }
  203. /* find the smaller of the total bytes we have available and what
  204. * the user is asking for */
  205. user_length = MIN(user_length, LOGRING_FIRST_EMPTY_BYTE - *user_offset);
  206. retval = user_length;
  207. /* figure out where to start copying data from, based on user's offset */
  208. start_point =
  209. (logring_readindex + (*user_offset-logring_offset)) % logring_size;
  210. /* copy the (possibly noncontiguous) data into user's buffer) */
  211. while (user_length) {
  212. n = MIN(user_length, logring_size - start_point);
  213. memcpy(user_buffer + bytes_copied, logring_data + start_point, n);
  214. bytes_copied += n;
  215. user_length -= n;
  216. start_point = (start_point + n) % logring_size;
  217. }
  218. /* advance the user's file pointer */
  219. *user_offset += retval;
  220. done:
  221. /* and complete the read system call */
  222. fusd_return(c->read, retval);
  223. c->read = NULL;
  224. }
  225. /*
  226. * read on /dev/logring: store the fusd_file_info pointer. then call
  227. * complete_read, which will immediately call fusd_return, if there is
  228. * data already waiting.
  229. *
  230. * Note that this shows a trick we use commonly in FUSD drivers: you
  231. * are allowed to call fusd_return() from within a callback as long as
  232. * you return -FUSD_NOREPLY. In other words, a driver can EITHER
  233. * return a real return value from its callback, OR call fusd_return
  234. * explicitly, but not both.
  235. */
  236. static ssize_t logring_read(struct fusd_file_info *file, char *buffer,
  237. size_t len, loff_t *offset)
  238. {
  239. struct logring_client *c = (struct logring_client *) file->private_data;
  240. if (c == NULL || c->read != NULL) {
  241. fprintf(stderr, "logring_read's arguments are confusd, alas");
  242. return -EINVAL;
  243. }
  244. c->read = file;
  245. logring_complete_read(c);
  246. return -FUSD_NOREPLY;
  247. }
  248. /*
  249. * complete_polldiff: if a client has an outstanding 'polldiff'
  250. * request, possibly return updated poll-state information to the
  251. * kernel, if indeed the state has changed.
  252. */
  253. void logring_complete_polldiff(struct logring_client *c)
  254. {
  255. int curr_state, cached_state;
  256. /* if there is no outstanding polldiff, do nothing */
  257. if (c == NULL || c->polldiff == NULL)
  258. return;
  259. /* figure out the "current" state: i.e. whether or not the logring
  260. * is readable for this client based on its current position in the
  261. * stream. The logring is *always* writable. */
  262. if (*(fusd_get_offset(c->polldiff)) < LOGRING_FIRST_EMPTY_BYTE)
  263. curr_state = FUSD_NOTIFY_INPUT | FUSD_NOTIFY_OUTPUT; /* read and write */
  264. else
  265. curr_state = FUSD_NOTIFY_OUTPUT; /* writable only */
  266. /* cached_state is what the kernel *thinks* the state is */
  267. cached_state = fusd_get_poll_diff_cached_state(c->polldiff);
  268. /* if the state is not what the kernel thinks it is, notify the
  269. kernel of the change */
  270. if (curr_state != cached_state) {
  271. fusd_return(c->polldiff, curr_state);
  272. c->polldiff = NULL;
  273. }
  274. }
  275. /* This function is only called on behalf of clients who are trying to
  276. * use select(). The kernel keeps us up to date on what it thinks the
  277. * current "poll state" is, i.e. readable and/or writable. The kernel
  278. * calls this function every time its assumption about the current
  279. * poll state changes. Every time the driver's notion of the state
  280. * differs from what the kernel thinks it is, it should return the
  281. * poll_diff request with the updated state. Note that a 2nd request
  282. * may come from the kernel before the driver has returned the first
  283. * one; if this happens, use fusd_destroy() to get rid of the older one.
  284. */
  285. int logring_polldiff(struct fusd_file_info *file, unsigned int flags)
  286. {
  287. struct logring_client *c = (struct logring_client *) file->private_data;
  288. if (c == NULL)
  289. return -EIO;
  290. /* if we're already holding a polldiff request that we haven't
  291. * replied to yet, destroy the old one and hold onto only the new
  292. * one */
  293. if (c->polldiff != NULL) {
  294. fusd_destroy(c->polldiff);
  295. c->polldiff = NULL;
  296. }
  297. c->polldiff = file;
  298. logring_complete_polldiff(c);
  299. return -FUSD_NOREPLY;
  300. }
  301. /*
  302. * a write on /dev/logring: first, copy the data from the user into our
  303. * data queue. Then, complete any reads and polldiffs that might be
  304. * outstanding.
  305. */
  306. ssize_t logring_write(struct fusd_file_info *file, const char *buffer,
  307. size_t len, loff_t *offset)
  308. {
  309. struct logring_client *c;
  310. int overflow = 0, bytes_copied = 0, n, retval;
  311. /* if the message is longer than the buffer, just take the beginning
  312. * of it, in hopes that the reader (if any) will have time to read
  313. * before we wrap around and obliterate it */
  314. len = MIN(len, logring_size - 1);
  315. retval = len;
  316. if (len + LOGRING_QLEN >= (logring_size-1)) {
  317. overflow = 1;
  318. /* in case of overflow, figure out where the new buffer will
  319. * begin. we start by figuring out where the current buffer ENDS:
  320. * logring_offset + LOGRING_QLEN. we then advance the end-offset
  321. * by the length of the current write, and work backwards to
  322. * figure out what the oldest unoverwritten data will be (i.e.,
  323. * size of the buffer). was that all quite clear? :-) */
  324. logring_offset = logring_offset + LOGRING_QLEN + len - logring_size + 1;
  325. }
  326. while (len) {
  327. /* how many contiguous bytes are available from the write point to
  328. * the end of the circular buffer? */
  329. n = MIN(len, logring_size - logring_writeindex);
  330. memcpy(logring_data + logring_writeindex, buffer + bytes_copied, n);
  331. bytes_copied += n;
  332. len -= n;
  333. logring_writeindex = (logring_writeindex + n) % logring_size;
  334. }
  335. /* if there was an overflow (i.e., new data wrapped around and
  336. * overwrote old data that had not yet been read), then, reset the
  337. * read point to be whatever the oldest data is that we have. */
  338. if (overflow)
  339. logring_readindex = (logring_writeindex + 1) % logring_size;
  340. /* now, complete any blocked reads and/or polldiffs */
  341. for (c = client_list; c != NULL; c = c->next) {
  342. logring_complete_read(c);
  343. logring_complete_polldiff(c);
  344. }
  345. /* now tell the client how many bytes we acutally wrote */
  346. return retval;
  347. }
  348. int main(int argc, char *argv[])
  349. {
  350. char *name;
  351. /* size must be provided, and an optional logring name */
  352. if (argc != 2 && argc != 3) {
  353. fprintf(stderr, "usage: %s <logring-size> [logring-name]\n", argv[0]);
  354. exit(1);
  355. }
  356. name = (argc == 3 ? argv[2] : "/dev/logring");
  357. /* convert the arg to an int and alloc memory for the logring */
  358. if ((logring_size = atoi(argv[1])) <= 0) {
  359. fprintf(stderr, "invalid logring size; it must be >0\n");
  360. exit(1);
  361. }
  362. if ((logring_data = (char *) malloc(sizeof(char) * logring_size)) == NULL) {
  363. fprintf(stderr, "couldn't allocate %d bytes!\n", logring_size);
  364. exit(1);
  365. }
  366. /* register the fusd device */
  367. fusd_simple_register(name, "misc", "logring", 0666, NULL,
  368. open: logring_open, close: logring_close,
  369. read: logring_read, write: logring_write,
  370. poll_diff: logring_polldiff);
  371. printf("calling fusd_run; reads from /dev/logring will now block\n"
  372. "until someone writes to /dev/logring...\n");
  373. fusd_run();
  374. return 0;
  375. }