]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - ipc/ipcdev.git/blob - qnx/src/api/MessageQ.c
Moved Std.h into ti/ipc namespace for QNX.
[ipc/ipcdev.git] / qnx / src / api / MessageQ.c
1 /*
2  * Copyright (c) 2012-2013, Texas Instruments Incorporated
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * *  Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * *  Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * *  Neither the name of Texas Instruments Incorporated nor the names of
17  *    its contributors may be used to endorse or promote products derived
18  *    from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
24  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
27  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 /*============================================================================
33  *  @file   MessageQ.c
34  *
35  *  @brief  MessageQ module "client" implementation
36  *
37  *  This implementation is geared for use in a "client/server" model, whereby
38  *  system-wide data is maintained in a "server" component and process-
39  *  specific data is handled here.  At the moment, this implementation
40  *  connects and communicates with LAD for the server connection.
41  *
42  *  The MessageQ module supports the structured sending and receiving of
43  *  variable length messages. This module can be used for homogeneous or
44  *  heterogeneous multi-processor messaging.
45  *
46  *  MessageQ provides more sophisticated messaging than other modules. It is
47  *  typically used for complex situations such as multi-processor messaging.
48  *
49  *  The following are key features of the MessageQ module:
50  *  -Writers and readers can be relocated to another processor with no
51  *   runtime code changes.
52  *  -Timeouts are allowed when receiving messages.
53  *  -Readers can determine the writer and reply back.
54  *  -Receiving a message is deterministic when the timeout is zero.
55  *  -Messages can reside on any message queue.
56  *  -Supports zero-copy transfers.
57  *  -Can send and receive from any type of thread.
58  *  -Notification mechanism is specified by application.
59  *  -Allows QoS (quality of service) on message buffer pools. For example,
60  *   using specific buffer pools for specific message queues.
61  *
62  *  Messages are sent and received via a message queue. A reader is a thread
63  *  that gets (reads) messages from a message queue. A writer is a thread that
64  *  puts (writes) a message to a message queue. Each message queue has one
65  *  reader and can have many writers. A thread may read from or write to multiple
66  *  message queues.
67  *
68  *  Conceptually, the reader thread owns a message queue. The reader thread
69  *  creates a message queue. Writer threads  a created message queues to
70  *  get access to them.
71  *
72  *  Message queues are identified by a system-wide unique name. Internally,
73  *  MessageQ uses the NameServermodule for managing
74  *  these names. The names are used for opening a message queue. Using
75  *  names is not required.
76  *
77  *  Messages must be allocated from the MessageQ module. Once a message is
78  *  allocated, it can be sent on any message queue. Once a message is sent, the
79  *  writer loses ownership of the message and should not attempt to modify the
80  *  message. Once the reader receives the message, it owns the message. It
81  *  may either free the message or re-use the message.
82  *
83  *  Messages in a message queue can be of variable length. The only
84  *  requirement is that the first field in the definition of a message must be a
85  *  MsgHeader structure. For example:
86  *  typedef struct MyMsg {
87  *      MessageQ_MsgHeader header;
88  *      ...
89  *  } MyMsg;
90  *
91  *  The MessageQ API uses the MessageQ_MsgHeader internally. Your application
92  *  should not modify or directly access the fields in the MessageQ_MsgHeader.
93  *
94  *  All messages sent via the MessageQ module must be allocated from a
95  *  Heap implementation. The heap can be used for
96  *  other memory allocation not related to MessageQ.
97  *
98  *  An application can use multiple heaps. The purpose of having multiple
99  *  heaps is to allow an application to regulate its message usage. For
100  *  example, an application can allocate critical messages from one heap of fast
101  *  on-chip memory and non-critical messages from another heap of slower
102  *  external memory
103  *
104  *  MessageQ does support the usage of messages that allocated via the
105  *  alloc function. Please refer to the staticMsgInit
106  *  function description for more details.
107  *
108  *  In a multiple processor system, MessageQ communications to other
109  *  processors via MessageQTransport instances. There must be one and
110  *  only one MessageQTransport instance for each processor where communication
111  *  is desired.
112  *  So on a four processor system, each processor must have three
113  *  MessageQTransport instance.
114  *
115  *  The user only needs to create the MessageQTransport instances. The instances
116  *  are responsible for registering themselves with MessageQ.
117  *  This is accomplished via the registerTransport function.
118  *
119  *  ============================================================================
120  */
123 /* Standard headers */
124 #include <ti/ipc/Std.h>
126 /* Linux specific header files, replacing OSAL: */
127 #include <pthread.h>
129 /* Module level headers */
130 #include <ti/ipc/NameServer.h>
131 #include <ti/ipc/MultiProc.h>
132 #include <ti/syslink/inc/_MultiProc.h>
133 #include <ti/ipc/MessageQ.h>
134 #include <_MessageQ.h>
135 #include <_IpcLog.h>
136 #include <ti/syslink/inc/MessageQDrvDefs.h>
138 #include <sys/select.h>
139 #include <sys/time.h>
140 #include <sys/types.h>
141 #include <sys/param.h>
143 #include <errno.h>
144 #include <stdio.h>
145 #include <string.h>
146 #include <stdlib.h>
147 #include <unistd.h>
148 #include <assert.h>
149 #include <fcntl.h>
151 #include <ti/syslink/inc/usr/Qnx/MessageQDrv.h>
153 /* TI IPC utils: */
154 #include <TiIpcFxns.h>
156 #include <ti/syslink/inc/ti/ipc/ti_ipc.h>
158 /* =============================================================================
159  * Macros/Constants
160  * =============================================================================
161  */
163 /*!
164  *  @brief  Name of the reserved NameServer used for MessageQ.
165  */
166 #define MessageQ_NAMESERVER  "MessageQ"
168 /* More magic rpmsg port numbers: */
169 #define MESSAGEQ_RPMSG_PORT       61
170 #define MESSAGEQ_RPMSG_MAXSIZE   512
171 #define RPMSG_RESERVED_ADDRESSES  (1024)
173 /* Trace flag settings: */
174 #define TRACESHIFT    12
175 #define TRACEMASK     0x1000
177 /* =============================================================================
178  * Structures & Enums
179  * =============================================================================
180  */
182 /* structure for MessageQ module state */
183 typedef struct MessageQ_ModuleObject {
184     Int                 refCount;
185     /*!< Reference count */
186     NameServer_Handle   nameServer;
187     /*!< Handle to the local NameServer used for storing GP objects */
188     pthread_mutex_t     gate;
189     /*!< Handle of gate to be used for local thread safety */
190     MessageQ_Params     defaultInstParams;
191     /*!< Default instance creation parameters */
192     int                 ipcFd[MultiProc_MAXPROCESSORS];
193     /*!< File Descriptors for sending to each remote processor */
194     int                 seqNum;
195     /*!< Process-specific sequence number */
196 } MessageQ_ModuleObject;
198 /*!
199  *  @brief  Structure for the Handle for the MessageQ.
200  */
201 typedef struct MessageQ_Object_tag {
202     MessageQ_Params         params;
203     /*! Instance specific creation parameters */
204     MessageQ_QueueId        queue;
205     /* Unique id */
206     int                     ipcFd;
207     /* File Descriptors to receive from a message queue. */
208     int                     unblockFdW;
209     /* Write this fd to unblock the select() call in MessageQ _get() */
210     int                     unblockFdR;
211      /* File Descriptor to block on to listen to unblockFdW. */
212     void                    *serverHandle;
213 } MessageQ_Object;
215 static Bool verbose = FALSE;
217 /* =============================================================================
218  *  Globals
219  * =============================================================================
220  */
221 static MessageQ_ModuleObject MessageQ_state =
223     .refCount               = 0,
224     .nameServer             = NULL,
225 };
227 /*!
228  *  @var    MessageQ_module
229  *
230  *  @brief  Pointer to the MessageQ module state.
231  */
232 MessageQ_ModuleObject * MessageQ_module = &MessageQ_state;
235 /* =============================================================================
236  * Forward declarations of internal functions
237  * =============================================================================
238  */
240 /* This is a helper function to initialize a message. */
241 static Int transportCreateEndpoint(int * fd, UInt16 queueIndex);
242 static Int transportCloseEndpoint(int fd);
243 static Int transportGet(int fd, MessageQ_Msg * retMsg);
244 static Int transportPut(MessageQ_Msg msg, UInt16 dstId, UInt16 dstProcId);
246 /* =============================================================================
247  * APIS
248  * =============================================================================
249  */
250 /* Function to get default configuration for the MessageQ module.
251  *
252  */
253 Void MessageQ_getConfig (MessageQ_Config * cfg)
255     Int status;
256     MessageQDrv_CmdArgs cmdArgs;
258     assert (cfg != NULL);
260     cmdArgs.args.getConfig.config = cfg;
261     status = MessageQDrv_ioctl (CMD_MESSAGEQ_GETCONFIG, &cmdArgs);
263     if (status < 0) {
264         PRINTVERBOSE1("MessageQ_getConfig: API (through IOCTL) failed, \
265             status=%d\n", status)
266     }
268     return;
271 /* Function to setup the MessageQ module. */
272 Int MessageQ_setup (const MessageQ_Config * cfg)
274     Int status;
275     MessageQDrv_CmdArgs cmdArgs;
277     Int i;
279     cmdArgs.args.setup.config = (MessageQ_Config *) cfg;
280     status = MessageQDrv_ioctl(CMD_MESSAGEQ_SETUP, &cmdArgs);
281     if (status < 0) {
282         PRINTVERBOSE1("MessageQ_setup: API (through IOCTL) failed, \
283             status=%d\n", status)
284         return status;
285     }
287     MessageQ_module->nameServer = cmdArgs.args.setup.nameServerHandle;
288     MessageQ_module->seqNum = 0;
290     /* Create a default local gate. */
291     pthread_mutex_init (&(MessageQ_module->gate), NULL);
293     /* Clear ipcFd array. */
294     for (i = 0; i < MultiProc_MAXPROCESSORS; i++) {
295        MessageQ_module->ipcFd[i]      = -1;
296     }
298     return status;
301 /*
302  * Function to destroy the MessageQ module.
303  */
304 Int MessageQ_destroy (void)
306     Int status;
307     MessageQDrv_CmdArgs    cmdArgs;
309     status = MessageQDrv_ioctl (CMD_MESSAGEQ_DESTROY, &cmdArgs);
310     if (status < 0) {
311         PRINTVERBOSE1("MessageQ_destroy: API (through IOCTL) failed, \
312             status=%d\n", status)
313     }
315     return status;
318 /* Function to initialize the parameters for the MessageQ instance. */
319 Void MessageQ_Params_init (MessageQ_Params * params)
321     memcpy (params, &(MessageQ_module->defaultInstParams),
322             sizeof (MessageQ_Params));
324     return;
327 /*
328  *   Function to create a MessageQ object for receiving.
329  *
330  *   Create a file descriptor and bind the source address
331  *   (local ProcId/MessageQ ID) in
332  *   order to get messages dispatched to this messageQ.
333  */
334 MessageQ_Handle MessageQ_create (String name, const MessageQ_Params * params)
336     Int                   status    = MessageQ_S_SUCCESS;
337     MessageQ_Object *     obj    = NULL;
338     UInt16                queueIndex = 0u;
339     UInt16                procId;
340     MessageQDrv_CmdArgs   cmdArgs;
341     int                   fildes[2];
343     cmdArgs.args.create.params = (MessageQ_Params *) params;
344     cmdArgs.args.create.name = name;
345     if (name != NULL) {
346         cmdArgs.args.create.nameLen = (strlen (name) + 1);
347     }
348     else {
349         cmdArgs.args.create.nameLen = 0;
350     }
352     status = MessageQDrv_ioctl (CMD_MESSAGEQ_CREATE, &cmdArgs);
353     if (status < 0) {
354         PRINTVERBOSE1("MessageQ_create: API (through IOCTL) failed, \
355             status=%d\n", status)
356         return NULL;
357     }
359     /* Create the generic obj */
360     obj = (MessageQ_Object *)calloc(1, sizeof (MessageQ_Object));
362     if (params != NULL) {
363        /* Populate the params member */
364         memcpy((Ptr) &obj->params, (Ptr)params, sizeof (MessageQ_Params));
365     }
367     procId = MultiProc_self();
368     queueIndex = (MessageQ_QueueIndex)cmdArgs.args.create.queueId;
369     obj->queue = cmdArgs.args.create.queueId;
370     obj->serverHandle = cmdArgs.args.create.handle;
372     PRINTVERBOSE2("MessageQ_create: creating endpoint for: %s, \
373        queueIndex: %d\n", name, queueIndex)
374     status = transportCreateEndpoint(&obj->ipcFd, queueIndex);
375     if (status < 0) {
376        goto cleanup;
377     }
379     /*
380      * Now, to support MessageQ_unblock() functionality, create an event object.
381      * Writing to this event will unblock the select() call in MessageQ_get().
382      */
383     if (pipe(fildes) == -1) {
384         printf ("MessageQ_create: pipe creation failed: %d, %s\n",
385                    errno, strerror(errno));
386         status = MessageQ_E_FAIL;
387     }
388     obj->unblockFdW = fildes[1];
389     obj->unblockFdR = fildes[0];
391 cleanup:
392     /* Cleanup if fail: */
393     if (status < 0) {
394         MessageQ_delete((MessageQ_Handle *)&obj);
395     }
397     return ((MessageQ_Handle) obj);
400 /*
401  * Function to delete a MessageQ object for a specific slave processor.
402  *
403  * Deletes the file descriptors associated with this MessageQ object.
404  */
405 Int MessageQ_delete (MessageQ_Handle * handlePtr)
407     Int               status    = MessageQ_S_SUCCESS;
408     MessageQ_Object * obj       = NULL;
409     MessageQDrv_CmdArgs cmdArgs;
411     obj = (MessageQ_Object *) (*handlePtr);
413     cmdArgs.args.deleteMessageQ.handle = obj->serverHandle;
414     status = MessageQDrv_ioctl (CMD_MESSAGEQ_DELETE, &cmdArgs);
415     if (status < 0) {
416         PRINTVERBOSE1("MessageQ_delete: API (through IOCTL) failed, \
417             status=%d\n", status)
418     }
420     /* Close the fds used for MessageQ_unblock(): */
421     close(obj->unblockFdW);
422     close(obj->unblockFdR);
424     /* Close the communication endpoint: */
425     status = transportCloseEndpoint(obj->ipcFd);
427     /* Now free the obj */
428     free (obj);
429     *handlePtr = NULL;
431     return (status);
434 /*
435  *  Opens an instance of MessageQ for sending.
436  *
437  *  We need not create a tiipc file descriptor here; the file descriptors for
438  *  all remote processors were created during MessageQ_attach(), and will be
439  *  retrieved during MessageQ_put().
440  */
441 Int MessageQ_open (String name, MessageQ_QueueId * queueId)
443     Int status = MessageQ_S_SUCCESS;
445     status = NameServer_getUInt32 (MessageQ_module->nameServer,
446                                      name, queueId, NULL);
448     if (status == NameServer_E_NOTFOUND) {
449         /* Set return queue ID to invalid. */
450         *queueId = MessageQ_INVALIDMESSAGEQ;
451         status = MessageQ_E_NOTFOUND;
452     }
453     else if (status >= 0) {
454         /* Override with a MessageQ status code. */
455         status = MessageQ_S_SUCCESS;
456     }
457     else {
458         /* Set return queue ID to invalid. */
459         *queueId = MessageQ_INVALIDMESSAGEQ;
460         /* Override with a MessageQ status code. */
461         if (status == NameServer_E_TIMEOUT) {
462             status = MessageQ_E_TIMEOUT;
463         }
464         else {
465             status = MessageQ_E_FAIL;
466         }
467     }
469     return (status);
472 /* Closes previously opened instance of MessageQ module. */
473 Int MessageQ_close (MessageQ_QueueId * queueId)
475     Int32 status = MessageQ_S_SUCCESS;
477     /* Nothing more to be done for closing the MessageQ. */
478     *queueId = MessageQ_INVALIDMESSAGEQ;
480     return (status);
483 /*
484  * Place a message onto a message queue.
485  *
486  * Calls TransportShm_put(), which handles the sending of the message using the
487  * appropriate kernel interface (socket, device ioctl) call for the remote
488  * procId encoded in the queueId argument.
489  *
490  */
491 Int MessageQ_put (MessageQ_QueueId queueId, MessageQ_Msg msg)
493     Int      status;
494     UInt16   dstProcId  = (UInt16)(queueId >> 16);
495     UInt16   queueIndex = (MessageQ_QueueIndex)(queueId & 0x0000ffff);
497     msg->dstId     = queueIndex;
498     msg->dstProc   = dstProcId;
500     status = transportPut(msg, queueIndex, dstProcId);
502     return (status);
505 /*
506  * Gets a message for a message queue and blocks if the queue is empty.
507  * If a message is present, it returns it.  Otherwise it blocks
508  * waiting for a message to arrive.
509  * When a message is returned, it is owned by the caller.
510  *
511  * We block using select() on the receiving tiipc file descriptor, then
512  * get the waiting message via a read.
513  * We use the file descriptors stored in the messageQ object via a previous
514  * call to MessageQ_create().
515  *
516  * Note: We currently do not support messages to be sent between threads on the
517  * lcoal processor.
518  *
519  */
520 Int MessageQ_get (MessageQ_Handle handle, MessageQ_Msg * msg ,UInt timeout)
522     Int     status = MessageQ_S_SUCCESS;
523     Int     tmpStatus;
524     MessageQ_Object * obj = (MessageQ_Object *) handle;
525     int     retval;
526     int     nfds;
527     fd_set  rfds;
528     struct  timeval tv;
529     void    *timevalPtr;
530     int     maxfd = 0;
532     /* Wait (with timeout) and retreive message */
533     FD_ZERO(&rfds);
534     FD_SET(obj->ipcFd, &rfds);
535     maxfd = obj->ipcFd;
537     /* Wait also on the event fd, which may be written by MessageQ_unblock(): */
538     FD_SET(obj->unblockFdR, &rfds);
540     if (timeout == MessageQ_FOREVER) {
541         timevalPtr = NULL;
542     }
543     else {
544         /* Timeout given in msec: convert:  */
545         tv.tv_sec = timeout / 1000;
546         tv.tv_usec = (timeout % 1000) * 1000;
547         timevalPtr = &tv;
548     }
549     /* Add one to last fd created: */
550     nfds = ((maxfd > obj->unblockFdR) ? maxfd : obj->unblockFdR) + 1;
552     retval = select(nfds, &rfds, NULL, NULL, timevalPtr);
553     if (retval)  {
554         if (FD_ISSET(obj->unblockFdR, &rfds))  {
555             /*
556              * Our event was signalled by MessageQ_unblock().
557              *
558              * This is typically done during a shutdown sequence, where
559              * the intention of the client would be to ignore (i.e. not fetch)
560              * any pending messages in the transport's queue.
561              * Thus, we shall not check for nor return any messages.
562              */
563             *msg = NULL;
564             status = MessageQ_E_UNBLOCKED;
565         }
566         else {
567             if (FD_ISSET(obj->ipcFd, &rfds)) {
568                 /* Our transport's fd was signalled: Get the message: */
569                 tmpStatus = transportGet(obj->ipcFd, msg);
570                 if (tmpStatus < 0) {
571                     printf ("MessageQ_get: tranposrtshm_get failed.");
572                     status = MessageQ_E_FAIL;
573                 }
574             }
575         }
576     }
577     else if (retval == 0) {
578         *msg = NULL;
579         status = MessageQ_E_TIMEOUT;
580     }
582     return (status);
585 /*
586  * Return a count of the number of messages in the queue
587  *
588  * TBD: To be implemented. Return -1 for now.
589  */
590 Int MessageQ_count (MessageQ_Handle handle)
592     Int               count = -1;
593     return (count);
596 /* Initializes a message not obtained from MessageQ_alloc. */
597 Void MessageQ_staticMsgInit (MessageQ_Msg msg, UInt32 size)
599     /* Fill in the fields of the message */
600     MessageQ_msgInit (msg);
601     msg->heapId  = MessageQ_STATICMSG;
602     msg->msgSize = size;
605 /*
606  * Allocate a message and initialize the needed fields (note some
607  * of the fields in the header are set via other APIs or in the
608  * MessageQ_put function,
609  */
610 MessageQ_Msg MessageQ_alloc (UInt16 heapId, UInt32 size)
612     MessageQ_Msg msg       = NULL;
614     /*
615      * heapId not used for local alloc (as this is over a copy transport), but
616      * we need to send to other side as heapId is used in BIOS transport:
617      */
618     msg = (MessageQ_Msg)calloc (1, size);
619     MessageQ_msgInit (msg);
620     msg->msgSize = size;
621     msg->heapId  = heapId;
623     return msg;
626 /* Frees the message back to the heap that was used to allocate it. */
627 Int MessageQ_free (MessageQ_Msg msg)
629     UInt32         status = MessageQ_S_SUCCESS;
631     /* Check to ensure this was not allocated by user: */
632     if (msg->heapId == MessageQ_STATICMSG)  {
633         status =  MessageQ_E_CANNOTFREESTATICMSG;
634     }
635     else {
636         free (msg);
637     }
639     return status;
642 /* Register a heap with MessageQ. */
643 Int MessageQ_registerHeap (Ptr heap, UInt16 heapId)
645     Int  status = MessageQ_S_SUCCESS;
647     /* Do nothing, as this uses a copy transport: */
649     return status;
652 /* Unregister a heap with MessageQ. */
653 Int MessageQ_unregisterHeap (UInt16 heapId)
655     Int  status = MessageQ_S_SUCCESS;
657     /* Do nothing, as this uses a copy transport: */
659     return status;
662 /* Unblocks a MessageQ */
663 Void MessageQ_unblock (MessageQ_Handle handle)
665     MessageQ_Object * obj   = (MessageQ_Object *) handle;
666     char         buf = 'n';
667     int          numBytes;
669     /* Write to pipe to awaken any threads blocked on this messageQ: */
670     numBytes = write(obj->unblockFdW, &buf, 1);
673 /* Embeds a source message queue into a message. */
674 Void MessageQ_setReplyQueue (MessageQ_Handle handle, MessageQ_Msg msg)
676     MessageQ_Object * obj   = (MessageQ_Object *) handle;
678     msg->replyId   = (UInt16)(obj->queue);
679     msg->replyProc = (UInt16)(obj->queue >> 16);
682 /* Returns the QueueId associated with the handle. */
683 MessageQ_QueueId MessageQ_getQueueId (MessageQ_Handle handle)
685     MessageQ_Object * obj = (MessageQ_Object *) handle;
686     UInt32            queueId;
688     queueId = (obj->queue);
690     return queueId;
693 /* Sets the tracing of a message */
694 Void MessageQ_setMsgTrace (MessageQ_Msg msg, Bool traceFlag)
696     msg->flags = (msg->flags & ~TRACEMASK) |   (traceFlag << TRACESHIFT);
699 /*
700  *  Returns the amount of shared memory used by one transport instance.
701  *
702  *  The MessageQ module itself does not use any shared memory but the
703  *  underlying transport may use some shared memory.
704  */
705 SizeT MessageQ_sharedMemReq (Ptr sharedAddr)
707     SizeT memReq = 0u;
709     /* Do nothing, as this is a copy transport. */
711     return (memReq);
714 /*
715  *  Opens a file descriptor for this remote proc.
716  *
717  *  Only opens it if one does not already exist for this procId.
718  *
719  *  Note: remoteProcId may be MultiProc_Self() for loopback case.
720  */
721 Int MessageQ_attach (UInt16 remoteProcId, Ptr sharedAddr)
723     Int     status = MessageQ_S_SUCCESS;
724     int     ipcFd;
725     int     err;
727     PRINTVERBOSE1("MessageQ_attach: remoteProcId: %d\n", remoteProcId)
729     if (remoteProcId >= MultiProc_MAXPROCESSORS) {
730         status = MessageQ_E_INVALIDPROCID;
731         goto exit;
732     }
734     pthread_mutex_lock (&(MessageQ_module->gate));
736     /* Only open a fd if one doesn't exist: */
737     if (MessageQ_module->ipcFd[remoteProcId] == -1)  {
738         /* Create a fd for sending messages to the remote proc: */
739         ipcFd = open("/dev/tiipc", O_RDWR);
740         if (ipcFd < 0) {
741             status = MessageQ_E_FAIL;
742             printf ("MessageQ_attach: open of tiipc device failed: %d, %s\n",
743                        errno, strerror(errno));
744         }
745         else  {
746             PRINTVERBOSE1("MessageQ_attach: opened tiipc fd for sending: %d\n",
747                 ipcFd)
748             MessageQ_module->ipcFd[remoteProcId] = ipcFd;
749             /*
750              * Connect to the remote endpoint and bind any reserved address as
751              * local endpoint
752              */
753             Connect(ipcFd, remoteProcId, MESSAGEQ_RPMSG_PORT);
754             err = BindAddr(ipcFd, TIIPC_ADDRANY);
755             if (err < 0) {
756                 status = MessageQ_E_FAIL;
757                 printf ("MessageQ_attach: bind failed: %d, %s\n",
758                     errno, strerror(errno));
759             }
760         }
761     }
762     else {
763         status = MessageQ_E_ALREADYEXISTS;
764     }
766     pthread_mutex_unlock (&(MessageQ_module->gate));
768 exit:
769     return (status);
772 /*
773  *  Close the fd for this remote proc.
774  *
775  */
776 Int MessageQ_detach (UInt16 remoteProcId)
778     Int status = MessageQ_S_SUCCESS;
779     int ipcFd;
781     if (remoteProcId >= MultiProc_MAXPROCESSORS) {
782         status = MessageQ_E_INVALIDPROCID;
783         goto exit;
784     }
786     pthread_mutex_lock (&(MessageQ_module->gate));
788     ipcFd = MessageQ_module->ipcFd[remoteProcId];
789     if (close (ipcFd)) {
790         status = MessageQ_E_OSFAILURE;
791         printf("MessageQ_detach: close failed: %d, %s\n",
792                        errno, strerror(errno));
793     }
794     else {
795         PRINTVERBOSE1("MessageQ_detach: closed fd: %d\n", ipcFd)
796         MessageQ_module->ipcFd[remoteProcId] = -1;
797     }
799     pthread_mutex_unlock (&(MessageQ_module->gate));
801 exit:
802     return (status);
805 /*
806  * This is a helper function to initialize a message.
807  */
808 Void MessageQ_msgInit (MessageQ_Msg msg)
810     msg->reserved0 = 0;  /* We set this to distinguish from NameServerMsg */
811     msg->replyId   = (UInt16)MessageQ_INVALIDMESSAGEQ;
812     msg->msgId     = MessageQ_INVALIDMSGID;
813     msg->dstId     = (UInt16)MessageQ_INVALIDMESSAGEQ;
814     msg->flags     = MessageQ_HEADERVERSION | MessageQ_NORMALPRI;
815     msg->srcProc   = MultiProc_self();
817     pthread_mutex_lock(&(MessageQ_module->gate));
818     msg->seqNum  = MessageQ_module->seqNum++;
819     pthread_mutex_unlock(&(MessageQ_module->gate));
822 /*
823  * =============================================================================
824  * Transport: Fxns kept here until need for a transport layer is realized.
825  * =============================================================================
826  */
827 /*
828  * ======== transportCreateEndpoint ========
829  *
830  * Create a communication endpoint to receive messages.
831  */
832 static Int transportCreateEndpoint(int * fd, UInt16 queueIndex)
834     Int          status    = MessageQ_S_SUCCESS;
835     int          err;
837     /* Create a fd to the ti-ipc to receive messages for this messageQ */
838     *fd= open("/dev/tiipc", O_RDWR);
839     if (*fd < 0) {
840         status = MessageQ_E_FAIL;
841         printf ("transportCreateEndpoint: Couldn't open tiipc device: %d, %s\n",
842                   errno, strerror(errno));
844         goto exit;
845     }
847     PRINTVERBOSE1("transportCreateEndpoint: opened fd: %d\n", *fd)
849     err = BindAddr(*fd, (UInt32)queueIndex);
850     if (err < 0) {
851         status = MessageQ_E_FAIL;
852         printf ("transportCreateEndpoint: bind failed: %d, %s\n",
853                   errno, strerror(errno));
854     }
856 exit:
857     return (status);
860 /*
861  * ======== transportCloseEndpoint ========
862  *
863  *  Close the communication endpoint.
864  */
865 static Int transportCloseEndpoint(int fd)
867     Int status = MessageQ_S_SUCCESS;
869     PRINTVERBOSE1("transportCloseEndpoint: closing fd: %d\n", fd)
871     /* Stop communication to this endpoint */
872     close(fd);
874     return (status);
877 /*
878  * ======== transportGet ========
879  *  Retrieve a message waiting in the queue.
880 */
881 static Int transportGet(int fd, MessageQ_Msg * retMsg)
883     Int           status    = MessageQ_S_SUCCESS;
884     MessageQ_Msg  msg;
885     int           ret;
886     int           byteCount;
887     tiipc_remote_params remote;
889     /*
890      * We have no way of peeking to see what message size we'll get, so we
891      * allocate a message of max size to receive contents from tiipc
892      * (currently, a copy transport)
893      */
894     msg = MessageQ_alloc (0, MESSAGEQ_RPMSG_MAXSIZE);
895     if (!msg)  {
896         status = MessageQ_E_MEMORY;
897         goto exit;
898     }
900     /* Get message */
901     byteCount = read(fd, msg, MESSAGEQ_RPMSG_MAXSIZE);
902     if (byteCount < 0) {
903         printf("read failed: %s (%d)\n", strerror(errno), errno);
904         status = MessageQ_E_FAIL;
905         goto exit;
906     }
907     else {
908          /* Update the allocated message size (even though this may waste space
909           * when the actual message is smaller than the maximum rpmsg size,
910           * the message will be freed soon anyway, and it avoids an extra copy).
911           */
912          msg->msgSize = byteCount;
914          /*
915           * If the message received was statically allocated, reset the
916           * heapId, so the app can free it.
917           */
918          if (msg->heapId == MessageQ_STATICMSG)  {
919              msg->heapId = 0;  /* for a copy transport, heap id is 0. */
920          }
921     }
923     PRINTVERBOSE1("transportGet: read from fd: %d\n", fd)
924     ret = ioctl(fd, TIIPC_IOCGETREMOTE, &remote);
925     PRINTVERBOSE3("\tReceived a msg: byteCount: %d, rpmsg addr: %d, rpmsg \
926         proc: %d\n", byteCount, remote.remote_addr, remote.remote_proc)
927     PRINTVERBOSE2("\tMessage Id: %d, Message size: %d\n", msg->msgId, msg->msgSize)
929     *retMsg = msg;
931 exit:
932     return (status);
935 /*
936  * ======== transportPut ========
937  *
938  * Write to tiipc file descriptor associated with
939  * with this destination procID.
940  */
941 static Int transportPut(MessageQ_Msg msg, UInt16 dstId, UInt16 dstProcId)
943     Int     status    = MessageQ_S_SUCCESS;
944     int     ipcFd;
945     int     err;
947     /*
948      * Retrieve the tiipc file descriptor associated with this
949      * transport for the destination processor.
950      */
951     ipcFd = MessageQ_module->ipcFd[dstProcId];
953     PRINTVERBOSE2("Sending msgId: %d via fd: %d\n", msg->msgId, ipcFd)
955     /* send response message to remote processor */
956     err = write(ipcFd, msg, msg->msgSize);
957     if (err < 0) {
958         printf ("transportPut: write failed: %d, %s\n",
959                   errno, strerror(errno));
960         status = MessageQ_E_FAIL;
961     }
963     /*
964      * Free the message, as this is a copy transport, we maintain MessageQ
965      * semantics.
966      */
967     MessageQ_free (msg);
969     return (status);