blob: d27c6bf851c2c9c2a8f67ad6cc7a179b7baf8f55 [file] [log] [blame]
Brian Silverman14fd0fb2014-01-14 21:42:01 -08001#ifndef AOS_LINUX_CODE_IPC_LIB_QUEUE_H_
2#define AOS_LINUX_CODE_IPC_LIB_QUEUE_H_
brians343bc112013-02-10 01:53:46 +00003
Brian Silverman14fd0fb2014-01-14 21:42:01 -08004#include "aos/linux_code/ipc_lib/shared_mem.h"
Brian Silvermana6d1b562013-09-01 14:39:39 -07005#include "aos/common/mutex.h"
6#include "aos/common/condition.h"
Brian Silverman7faaec72014-05-26 16:25:38 -07007#include "aos/common/util/options.h"
8#include "aos/common/logging/logging.h"
brians343bc112013-02-10 01:53:46 +00009
10// TODO(brians) add valgrind client requests to the queue and shared_mem_malloc
11// code to make checking for leaks work better
12// <http://www.valgrind.org/docs/manual/mc-manual.html#mc-manual.mempools>
13// describes how
14
brians343bc112013-02-10 01:53:46 +000015// Any pointers returned from these functions can be safely passed to other
16// processes because they are all shared memory pointers.
17// IMPORTANT: Any message pointer must be passed back in some way
Brian Silvermana6d1b562013-09-01 14:39:39 -070018// (FreeMessage and WriteMessage are common ones) or the
brians343bc112013-02-10 01:53:46 +000019// application will leak shared memory.
Brian Silvermana6d1b562013-09-01 14:39:39 -070020// NOTE: Taking a message from ReadMessage and then passing it to WriteMessage
21// might work, but it is not guaranteed to.
brians343bc112013-02-10 01:53:46 +000022
Brian Silvermana6d1b562013-09-01 14:39:39 -070023namespace aos {
brians343bc112013-02-10 01:53:46 +000024
Brian Silvermana6d1b562013-09-01 14:39:39 -070025// Queues are the primary way to use shared memory. Basic use consists of
26// calling Queue::Fetch and then reading and/or writing messages.
27// Queues (as the name suggests) are a FIFO stack of messages. Each combination
28// of name and type signature will result in a different queue, which means
29// that if you only recompile some code that uses differently sized messages,
30// it will simply use a different queue than the old code.
Brian Silverman08661c72013-09-01 17:24:38 -070031class RawQueue {
Brian Silvermana6d1b562013-09-01 14:39:39 -070032 public:
33 // Retrieves (and creates if necessary) a queue. Each combination of name and
34 // signature refers to a completely independent queue.
35 // length is how large each message will be
36 // hash can differentiate multiple otherwise identical queues
37 // queue_length is how many messages the queue will be able to hold
Brian Silverman227ad482014-03-23 11:21:32 -070038 // Will never return NULL.
Brian Silverman08661c72013-09-01 17:24:38 -070039 static RawQueue *Fetch(const char *name, size_t length, int hash,
Brian Silvermana6d1b562013-09-01 14:39:39 -070040 int queue_length);
41 // Same as above, except sets up the returned queue so that it will put
42 // messages on *recycle when they are freed (after they have been released by
43 // all other readers/writers and are not in the queue).
44 // recycle_queue_length determines how many freed messages will be kept.
45 // Other code can retrieve the 2 queues separately (the recycle queue will
46 // have the same length and hash as the main one). However, any frees made
47 // using a queue with only (name,length,hash,queue_length) before the
48 // recycle queue has been associated with it will not go on to the recycle
49 // queue.
50 // NOTE: calling this function with the same (name,length,hash,queue_length)
51 // but multiple recycle_queue_lengths will result in each freed message being
52 // put onto an undefined one of the recycle queues.
Brian Silverman227ad482014-03-23 11:21:32 -070053 // Will never return NULL.
Brian Silverman08661c72013-09-01 17:24:38 -070054 static RawQueue *Fetch(const char *name, size_t length, int hash,
Brian Silvermana6d1b562013-09-01 14:39:39 -070055 int queue_length,
56 int recycle_hash, int recycle_queue_length,
Brian Silverman08661c72013-09-01 17:24:38 -070057 RawQueue **recycle);
brians343bc112013-02-10 01:53:46 +000058
Brian Silvermaneb51cbb2014-03-14 22:57:08 -070059 // Doesn't update the currently read index (the read messages in the queue or
60 // the index). This means the returned message (and any others skipped with
61 // kFromEnd) will be left in the queue.
Brian Silvermana6d1b562013-09-01 14:39:39 -070062 // For reading only.
Brian Silverman7faaec72014-05-26 16:25:38 -070063 // Not valid for ReadMessageIndex combined with kFromEnd.
64 static constexpr Options<RawQueue>::Option kPeek{0x0001};
Brian Silvermana6d1b562013-09-01 14:39:39 -070065 // Reads the last message in the queue instead of just the next one.
66 // NOTE: This removes all of the messages until the last one from the queue
Brian Silvermaneb51cbb2014-03-14 22:57:08 -070067 // (which means that nobody else will read them).
Brian Silvermana6d1b562013-09-01 14:39:39 -070068 // For reading only.
Brian Silverman7faaec72014-05-26 16:25:38 -070069 // Not valid for ReadMessageIndex combined with kPeek.
70 static constexpr Options<RawQueue>::Option kFromEnd{0x0002};
Brian Silvermana6d1b562013-09-01 14:39:39 -070071 // Causes reads to return NULL and writes to fail instead of waiting.
72 // For reading and writing.
Brian Silverman7faaec72014-05-26 16:25:38 -070073 static constexpr Options<RawQueue>::Option kNonBlock{0x0004};
Brian Silvermana6d1b562013-09-01 14:39:39 -070074 // Causes things to block.
Brian Silvermana6d1b562013-09-01 14:39:39 -070075 // For reading and writing.
Brian Silverman7faaec72014-05-26 16:25:38 -070076 static constexpr Options<RawQueue>::Option kBlock{0x0008};
Brian Silvermana6d1b562013-09-01 14:39:39 -070077 // Causes writes to overwrite the oldest message in the queue instead of
78 // blocking.
79 // For writing only.
Brian Silverman7faaec72014-05-26 16:25:38 -070080 static constexpr Options<RawQueue>::Option kOverride{0x0010};
brians343bc112013-02-10 01:53:46 +000081
Brian Silvermana6d1b562013-09-01 14:39:39 -070082 // Writes a message into the queue.
83 // This function takes ownership of msg.
84 // NOTE: msg must point to a valid message from this queue
Brian Silverman227ad482014-03-23 11:21:32 -070085 // Returns true on success. A return value of false means msg has already been
86 // freed.
Brian Silverman7faaec72014-05-26 16:25:38 -070087 bool WriteMessage(void *msg, Options<RawQueue> options) {
88 static constexpr Options<RawQueue> kWriteFailureOptions =
89 kNonBlock | kBlock | kOverride;
90 if (!options.NoOthersSet(kWriteFailureOptions)) {
91 LOG(FATAL, "illegal write options in %x\n", options.printable());
92 }
93 if (!options.ExactlyOneSet(kWriteFailureOptions)) {
94 LOG(FATAL, "invalid write options %x\n", options.printable());
95 }
96 return DoWriteMessage(msg, options);
97 }
brians343bc112013-02-10 01:53:46 +000098
Brian Silvermana6d1b562013-09-01 14:39:39 -070099 // Reads a message out of the queue.
100 // The return value will have at least the length of this queue's worth of
101 // valid data where it's pointing to.
102 // The return value is const because other people might be viewing the same
103 // messsage. Do not cast the const away!
104 // IMPORTANT: The return value (if not NULL) must eventually be passed to
105 // FreeMessage.
Brian Silverman7faaec72014-05-26 16:25:38 -0700106 const void *ReadMessage(Options<RawQueue> options) {
107 CheckReadOptions(options);
108 return DoReadMessage(options);
109 }
Brian Silverman227ad482014-03-23 11:21:32 -0700110 // The same as ReadMessage, except it will never return the
111 // same message twice (when used with the same index argument). However,
112 // may not return some messages that pass through the queue.
Brian Silvermana6d1b562013-09-01 14:39:39 -0700113 // *index should start as 0. index does not have to be in shared memory, but
Brian Silvermancd2d84c2014-03-13 23:30:58 -0700114 // it can be.
Brian Silverman7faaec72014-05-26 16:25:38 -0700115 // Calling with both kPeek and kFromEnd in options isn't valid because that
116 // would mean ignoring index, which would make this function the same as
117 // ReadMessage (which should be used instead).
118 const void *ReadMessageIndex(Options<RawQueue> options, int *index) {
119 CheckReadOptions(options);
120 static constexpr Options<RawQueue> kFromEndAndPeek = kFromEnd | kPeek;
121 if (options.AllSet(kFromEndAndPeek)) {
122 LOG(FATAL, "ReadMessageIndex(kFromEnd | kPeek) is not allowed\n");
123 }
124 return DoReadMessageIndex(options, index);
125 }
brians343bc112013-02-10 01:53:46 +0000126
Brian Silvermana6d1b562013-09-01 14:39:39 -0700127 // Retrieves ("allocates") a message that can then be written to the queue.
128 // NOTE: the return value will be completely uninitialized
129 // The return value will have at least the length of this queue's worth of
130 // valid memory where it's pointing to.
131 // Returns NULL for error.
132 // IMPORTANT: The return value (if not NULL) must eventually be passed to
Brian Silverman227ad482014-03-23 11:21:32 -0700133 // FreeMessage or WriteMessage.
Brian Silvermana6d1b562013-09-01 14:39:39 -0700134 void *GetMessage();
brians343bc112013-02-10 01:53:46 +0000135
Brian Silverman797e71e2013-09-06 17:29:39 -0700136 // It is ok to call this method with a NULL msg.
137 void FreeMessage(const void *msg) {
138 if (msg != NULL) DecrementMessageReferenceCount(msg);
139 }
brians343bc112013-02-10 01:53:46 +0000140
Brian Silvermanc2e04222014-03-22 12:43:44 -0700141 // UNSAFE! Returns the number of free messages we have. Only safe to use when
142 // only 1 task is using this object (ie in tests).
143 int FreeMessages() const;
Brian Silvermaneb51cbb2014-03-14 22:57:08 -0700144
Brian Silvermana6d1b562013-09-01 14:39:39 -0700145 private:
146 struct MessageHeader;
Brian Silverman797e71e2013-09-06 17:29:39 -0700147
Brian Silverman7faaec72014-05-26 16:25:38 -0700148 // The public wrappers around these are inlined and do argument checking.
149 bool DoWriteMessage(void *msg, Options<RawQueue> options);
150 const void *DoReadMessage(Options<RawQueue> options);
151 const void *DoReadMessageIndex(Options<RawQueue> options, int *index);
152 void CheckReadOptions(Options<RawQueue> options) {
153 static constexpr Options<RawQueue> kValidOptions =
154 kPeek | kFromEnd | kNonBlock | kBlock;
155 if (!options.NoOthersSet(kValidOptions)) {
156 LOG(FATAL, "illegal read options in %x\n", options.printable());
157 }
158 static constexpr Options<RawQueue> kBlockChoices = kNonBlock | kBlock;
159 if (!options.ExactlyOneSet(kBlockChoices)) {
160 LOG(FATAL, "invalid read options %x\n", options.printable());
161 }
162 }
163
Brian Silverman4d0789d2014-03-23 17:03:07 -0700164 // Adds 1 to the given index and handles wrapping correctly.
165 int index_add1(int index);
166
Brian Silverman797e71e2013-09-06 17:29:39 -0700167 bool is_readable() { return data_end_ != data_start_; }
Brian Silverman4d0789d2014-03-23 17:03:07 -0700168 bool is_writable() { return index_add1(data_end_) != data_start_; }
brians343bc112013-02-10 01:53:46 +0000169
Brian Silvermana6d1b562013-09-01 14:39:39 -0700170 // These next 4 allow finding the right one.
171 const char *name_;
172 size_t length_;
173 int hash_;
174 int queue_length_;
175 // The next one in the linked list of queues.
Brian Silverman08661c72013-09-01 17:24:38 -0700176 RawQueue *next_;
brians343bc112013-02-10 01:53:46 +0000177
Brian Silverman08661c72013-09-01 17:24:38 -0700178 RawQueue *recycle_;
Brian Silvermana6d1b562013-09-01 14:39:39 -0700179
180 Mutex data_lock_; // protects operations on data_ etc
Brian Silverman797e71e2013-09-06 17:29:39 -0700181 // Always gets broadcasted to because different readers might have different
182 // ideas of what "readable" means (ie ones using separated indices).
Brian Silvermana6d1b562013-09-01 14:39:39 -0700183 Condition readable_;
184 Condition writable_;
185 int data_length_; // max length into data + 1
186 int data_start_; // is an index into data
187 int data_end_; // is an index into data
188 int messages_; // that have passed through
189 void **data_; // array of messages (with headers)
190
Brian Silvermana6d1b562013-09-01 14:39:39 -0700191 size_t msg_length_; // sizeof(each message) including the header
Brian Silvermanc2e04222014-03-22 12:43:44 -0700192 // A pointer to the first in the linked list of free messages.
193 MessageHeader *free_messages_;
Brian Silvermana6d1b562013-09-01 14:39:39 -0700194
Brian Silverman42d52372014-03-23 15:29:13 -0700195 // Keeps track of if the queue was writable before a read so we can Signal() a
196 // reader if we transition it.
197 bool writable_start_;
198
Brian Silverman35109802014-04-09 14:31:53 -0700199 // True iff somebody is currently Wait()ing on readable_.
200 // Set to true by each reader before calling Wait() and set back to false
201 // before the Broadcast().
202 bool readable_waiting_;
203
Brian Silvermana6d1b562013-09-01 14:39:39 -0700204 // Actually frees the given message.
205 void DoFreeMessage(const void *msg);
206 // Calls DoFreeMessage if appropriate.
207 void DecrementMessageReferenceCount(const void *msg);
Brian Silverman430e7fa2014-03-21 16:58:33 -0700208 // Only does the actual incrementing of the reference count.
209 void IncrementMessageReferenceCount(const void *msg) const;
Brian Silvermana6d1b562013-09-01 14:39:39 -0700210
Brian Silvermaneb51cbb2014-03-14 22:57:08 -0700211 // Must be called with data_lock_ locked.
Brian Silverman797e71e2013-09-06 17:29:39 -0700212 // *read_data will be initialized.
Brian Silvermana6d1b562013-09-01 14:39:39 -0700213 // Returns with a readable message in data_ or false.
Brian Silverman7faaec72014-05-26 16:25:38 -0700214 bool ReadCommonStart(Options<RawQueue> options, int *index);
Brian Silvermana6d1b562013-09-01 14:39:39 -0700215 // Deals with setting/unsetting readable_ and writable_.
Brian Silvermaneb51cbb2014-03-14 22:57:08 -0700216 // Must be called after data_lock_ has been unlocked.
Brian Silverman797e71e2013-09-06 17:29:39 -0700217 // read_data should be the same thing that was passed in to ReadCommonStart.
Brian Silverman42d52372014-03-23 15:29:13 -0700218 void ReadCommonEnd();
Brian Silverman227ad482014-03-23 11:21:32 -0700219 // Returns the index of the last message.
220 // Useful for reading with kPeek.
221 int LastMessageIndex() const;
Brian Silvermana6d1b562013-09-01 14:39:39 -0700222
223 // Gets called by Fetch when necessary (with placement new).
Brian Silverman08661c72013-09-01 17:24:38 -0700224 RawQueue(const char *name, size_t length, int hash, int queue_length);
Brian Silvermana6d1b562013-09-01 14:39:39 -0700225};
226
227} // namespace aos
228
Brian Silverman14fd0fb2014-01-14 21:42:01 -0800229#endif // AOS_LINUX_CODE_IPC_LIB_QUEUE_H_