1cbd314253790d53b08a10ec846f19ba54c11db9
[ipc/ipcdev.git] / linux / src / daemon / lad.c
1 /*
2  * Copyright (c) 2012-2015, 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  *  ======== lad.c ========
34  */
36 #include <ti/ipc/Std.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <sys/stat.h>
44 #include <sys/time.h>
45 #include <sys/types.h>
46 #include <signal.h>
47 #include <unistd.h>
49 #include <ti/ipc/MessageQ.h>
50 #include <_MessageQ.h>
51 #include <ti/ipc/NameServer.h>
52 #include <_NameServer.h>
53 #include <ti/ipc/GateMP.h>
54 #include <_GateMP_daemon.h>
55 #include <_MultiProc.h>
57 #include <GateHWSpinlock.h>
59 #include <ladclient.h>
60 #include <_lad.h>
62 #define DAEMON        1           /* 1 = run as a daemon; 0 = run as app */
64 Bool logFile = FALSE;
65 FILE *logPtr = NULL;
66 struct timeval start_tv;
68 static String commandFIFOFile = LAD_COMMANDFIFO;
69 static FILE *commandFIFOFilePtr = NULL;
71 #if defined(GATEMP_SUPPORT)
72 static Bool gatempEnabled = FALSE;
73 #endif
75 /* LAD client info arrays */
76 static Bool clientConnected[LAD_MAXNUMCLIENTS];
77 static UInt clientPID[LAD_MAXNUMCLIENTS];
78 static Char clientFIFOName[LAD_MAXNUMCLIENTS][LAD_MAXLENGTHFIFONAME];
79 static FILE * responseFIFOFilePtr[LAD_MAXNUMCLIENTS];
81 /* local internal routines */
82 static LAD_ClientHandle assignClientId(Void);
83 static Void cleanupDepartedClients(Void);
84 static Int connectToLAD(String clientName, Int pid, String clientProto, Int *clientIdPtr);
85 static Void disconnectFromLAD(Int clientId);
86 static Void doDisconnect(Int clientId);
88 struct LAD_CommandObj cmd;
89 union LAD_ResponseObj rsp;
91 #define LAD_USAGE "\
92 Usage:\n\
93     lad_<platform> [options] \n\
94 \n\
95 Options:\n\
96     h            : print this help message\n\
97     g            : enable GateMP support \n\
98     l <logfile>  : name of logfile for LAD\n\
99     p <oct value>: set LAD's directory permissions\n\
100     b <value>    : Processor's base cluster id \n\
101 \n\
102 Examples:\n\
103     lad_<platform> -h\n\
104     lad_<platform> -l log.txt\n\
105     lad_<platform> -l log.txt -p 777\n\
106     lad_<platform> -g -l log.txt\n\
107     lad_<platform> -l log.txt -b 10\n\
108 \n"
110 /*
111  *  ======== main ========
112  */
113 int main(int argc, char * argv[])
115     MessageQ_Handle handle;
116     UInt16 *procIdPtr;
117     Int statusIO;
118     Int clientId;
119     Int command;
120     Int flags;
121     Int i;
122     Int n;
123     Int c;
124 #if defined(GATEMP_SUPPORT)
125     Int status;
126 #endif
127     String tmpString;
128 #if DAEMON
129     pid_t pid;
130     pid_t sid;
131 #endif
133     /* change to LAD's root directory */
134     if ((chdir(LAD_ROOTDIR)) < 0) {
135         /* if can't change directory assume it needs to be created, do it */
136         if ((mkdir(LAD_ROOTDIR, 0666)) < 0) {
137             printf("\nERROR: Failed to create LAD's root directory!\n");
138             exit(EXIT_FAILURE);
139         }
140     }
142     /* change to LAD's working directory */
143     if ((chdir(LAD_WORKINGDIR)) < 0) {
145         /* if can't change directory assume it needs to be created, do it */
146         if ((mkdir(LAD_WORKINGDIR, 0666)) < 0) {
147             printf("\nERROR: Failed to create LAD's working directory!\n");
148             exit(EXIT_FAILURE);
149         }
150         /* now change to the new directory */
151         if ((chdir(LAD_WORKINGDIR)) < 0) {
152             printf("\nERROR: Failed to change to LAD's working directory!\n");
153             exit(EXIT_FAILURE);
154         }
155     }
157     /* process command line args */
158     while (1) {
159         c = getopt(argc, argv, "b:ghl:p:");
160         if (c == -1) {
161             break;
162         }
164         switch (c) {
165             case 'g':
166 #if defined(GATEMP_SUPPORT)
167                 printf("\nGateMP support enabled on host\n");
168                 gatempEnabled = TRUE;
169 #else
170                 printf("\nGateMP is not supported for this device\n");
171 #endif
172                 break;
173             case 'b':
174                 if (_MultiProc_cfg.id == 0xFFFF &&
175                     _MultiProc_cfg.baseIdOfCluster == 0xFFFF) {
176                     printf("\nSetting base cluster id to %s\n", optarg);
177                     _MultiProc_cfg.id = atoi(optarg);
178                     _MultiProc_cfg.baseIdOfCluster = atoi(optarg);
179                 }
180                 else {
181                    printf("\nBase cluster id in the MultiProcCfg file must be\n"
182                     "set to MultiProc_INVALIDID(0xFFFF) when using -b option\n");
183                    exit(EXIT_FAILURE);
184                 }
185                 break;
186             case 'h':
187                 printf("%s", LAD_USAGE);
188                 exit(0);
189                 break;
190             case 'l':
191                 logPtr = fopen(optarg, "w");
192                 if (logPtr == NULL) {
193                     printf("\nERROR: unable to open log file %s\n", optarg);
194                     exit(EXIT_FAILURE);
195                 }
196                 else {
197                     logFile = TRUE;
198                     gettimeofday(&start_tv, NULL);
199                     printf("\nOpened log file: %s\n", optarg);
200                     /* close log file upon LAD termination */
201                     flags = fcntl(fileno(logPtr), F_GETFD);
202                     if (flags != -1) {
203                         fcntl(fileno(logPtr), F_SETFD, flags | FD_CLOEXEC);
204                     }
205                 }
206                 break;
207             case 'p':
208                 printf("\nSet LAD's directory permissions to '%s'\n", optarg);
209                 chmod(LAD_ROOTDIR, strtol(optarg, NULL, 8));
210                 chmod(LAD_WORKINGDIR, strtol(optarg, NULL, 8));
211                 break;
212             default:
213                 fprintf (stderr, "\nUnrecognized argument\n");
214                 exit(EXIT_FAILURE);
215         }
216     }
218     /* Check to ensure id and baseId are not invalid */
219     printf ("id = %d baseId= %d\n", _MultiProc_cfg.id, _MultiProc_cfg.baseIdOfCluster);
220     if (_MultiProc_cfg.id == 0xFFFF || _MultiProc_cfg.baseIdOfCluster == 0xFFFF){
221          printf("\nBase cluster id is set to an INVALID value\n");
222          printf("Use -b option to set value or modify the MultiProcCfg file\n");
223          exit(EXIT_FAILURE);
224     }
227 #if DAEMON
228     /* fork off a child process */
229     pid = fork();
231     /* if fork of child failed then exit immediately; no child created */
232     if (pid < 0) {
233         printf("\nERROR: Failed to fork child process!");
234         exit(EXIT_FAILURE);
235     }
237     /* if pid > 0 this is the parent; time to die ... */
238     if (pid > 0) {
239         printf("\nSpawned daemon: %s\n\n", argv[0]);
240         exit(EXIT_SUCCESS);
241     }
243     /* child continues from here (pid == 0) ... */
245     /* change file mode mask */
246     umask(0);
248     /* create new session ID for the child */
249     sid = setsid();
251     /* exit with failure code if failed to get session ID... */
252     if (sid < 0) {
253         printf("\nERROR: Failed to acquire new session ID!");
254         exit(EXIT_FAILURE);
255     }
257     /* disassociate from the standard file descriptors */
258     close(STDIN_FILENO);
259     close(STDOUT_FILENO);
260     close(STDERR_FILENO);
262 #endif
264     LOG0("\nInitializing LAD... ")
266     /* TODO:L make sure LAD is not already running? */
268     /* initialize client info arrays */
269     for (i = 0; i < LAD_MAXNUMCLIENTS; i++) {
270         clientConnected[i] = FALSE;
271         responseFIFOFilePtr[i] = NULL;
272     }
274     /* if command FIFO exists from previous LAD session delete it now */
275     unlink(commandFIFOFile);
277     /* create command FIFO */
278     statusIO = mkfifo(commandFIFOFile, 0777);
279     if (statusIO != 0) {
280         LOG2("\nERROR: unable to create %s, errno = %x\n", commandFIFOFile,
281             errno)
282         return(0);
283     }
285     /* set FIFO permissions to read/write */
286     chmod(commandFIFOFile, 0666);
288     /* Setup modules relevant for GateMP if necessary */
289 #if defined(GATEMP_SUPPORT)
290     if (gatempEnabled) {
291         /* Set up NameServer for resource manager process */
292         status = NameServer_setup();
293         if (status < 0) {
294             LOG0("\nERROR: unable to setup NameServer\n")
295             return(0);
296         }
298         status = GateHWSpinlock_start();
299         if (status < 0) {
300             LOG0("\nERROR: unable to start GateHWSpinlock\n");
301             return(0);
302         }
304         /* Set up GateMP */
305         status = GateMP_setup();
306         if (status < 0) {
307             LOG0("\nERROR: unable to setup GateMP\n")
308             NameServer_destroy();
309             return(0);
310         }
311     }
312 #endif
314 opencommandFIFO:
316     /* now open file for FIFO - will block until writer arrives... */
317     LOG1("\n    opening FIFO: %s\n", commandFIFOFile)
318     commandFIFOFilePtr = fopen(commandFIFOFile, "r");
319     if (commandFIFOFilePtr == NULL) {
320         LOG0("\nERROR: unable to open command FIFO\n")
321         unlink(commandFIFOFile);
322 #if defined(GATEMP_SUPPORT)
323         if (gatempEnabled) {
324             GateMP_destroy();
325             NameServer_destroy();
326         }
327 #endif
328         return(0);
329     }
331     /* COMMAND PROCESSING LOOP */
332     while (1) {
333         LOG0("Retrieving command...\n")
335         /* read the next command packet */
336         n = fread(&cmd, LAD_COMMANDLENGTH, 1, commandFIFOFilePtr);
338         /*
339          * if last client closes FIFO then it must be closed and reopened ...
340          */
341         if (!n) {
342             LOG1("   EOF detected on FIFO, closing FIFO: %s\n", commandFIFOFile)
343             fclose(commandFIFOFilePtr);
345             goto opencommandFIFO;
346         }
348         /* cleanup for any connected/started clients that have departed */
349         cleanupDepartedClients();
351         command = cmd.cmd;
352         clientId = cmd.clientId;
354         /* process individual commands */
355         switch (command) {
356           /*
357            * Since cmd is a union of rcv and snd structs, don't write
358            * any snd elements before all rcv elements have been referenced
359            * (either saved in separate variables or passed to a function).
360            *
361            * cmd.cmd has already been saved in 'command'
362            * cmd.clientId has already been saved in 'clientId'
363            */
364           case LAD_CONNECT:
365             connectToLAD(cmd.args.connect.name, cmd.args.connect.pid,
366                          cmd.args.connect.protocol, NULL);
368             break;
370           case LAD_DISCONNECT:
371             disconnectFromLAD(clientId);
373             break;
375           case LAD_IPC_GETCONFIG:
376             Ipc_getConfig(&rsp.ipcConfig);
377             break;
379           case LAD_NAMESERVER_SETUP:
380             LOG0("LAD_NAMESERVER_SETUP: calling NameServer_setup()...\n")
382             rsp.status = NameServer_setup();
384             LOG1("    status = %d\n", rsp.status)
385             LOG0("DONE\n")
387             break;
389           case LAD_NAMESERVER_DESTROY:
390             LOG0("LAD_NAMESERVER_DESTROY: calling NameServer_destroy()...\n")
392             rsp.status = NameServer_destroy();
394             LOG1("    status = %d\n", rsp.status)
395             LOG0("DONE\n")
397             break;
399           case LAD_NAMESERVER_PARAMS_INIT:
400             LOG0("LAD_NAMESERVER_PARAMS_INIT: calling NameServer_Params_init()...\n")
402             NameServer_Params_init(&rsp.params);
404             LOG0("DONE\n")
406             break;
408           case LAD_NAMESERVER_CREATE:
409             LOG1("LAD_NAMESERVER_CREATE: calling NameServer_create('%s')...\n", cmd.args.create.name)
411             rsp.handle = NameServer_create(cmd.args.create.name,
412                                                &cmd.args.create.params);
414             LOG1("    handle = %p\n", rsp.handle)
415             LOG0("DONE\n")
417             break;
419           case LAD_NAMESERVER_DELETE:
420             LOG1("LAD_NAMESERVER_DELETE: calling NameServer_delete(%p)...\n", cmd.args.delete.handle)
422             rsp.delete.handle = cmd.args.delete.handle;
423             rsp.delete.status = NameServer_delete(&rsp.delete.handle);
425             LOG1("    status = %d\n", rsp.status)
426             LOG0("DONE\n")
428             break;
430           case LAD_NAMESERVER_ADD:
431             LOG1("LAD_NAMESERVER_ADD: calling NameServer_add(%p, ", cmd.args.add.handle)
432             LOG2("'%s', %p,", cmd.args.add.name, cmd.args.add.buf)
433             LOG1(" 0x%x)...\n", cmd.args.add.len)
435             rsp.entryPtr = NameServer_add(
436                 cmd.args.add.handle,
437                 cmd.args.add.name,
438                 cmd.args.add.buf,
439                 cmd.args.add.len);
441             LOG1("    entryPtr = %p\n", rsp.entryPtr)
442             LOG0("DONE\n")
444             break;
446           case LAD_NAMESERVER_GET:
447             LOG2("LAD_NAMESERVER_GET: calling NameServer_get(%p, '%s'",
448                 cmd.args.get.handle, cmd.args.get.name)
449             LOG0(")...\n")
451             if (cmd.args.get.procId[0] == (UInt16)-1) {
452                 procIdPtr = NULL;
453             }
454             else {
455                 procIdPtr = cmd.args.get.procId;
456             }
457             rsp.status = NameServer_get(
458                 cmd.args.get.handle,
459                 cmd.args.get.name,
460                 rsp.get.buf,
461                 &cmd.args.get.len,
462                 procIdPtr);
463             rsp.get.len = cmd.args.get.len;
465             LOG1("    value = 0x%x\n", rsp.get.len)
466             LOG1("    status = %d\n", rsp.status)
467             LOG0("DONE\n")
469             break;
471           case LAD_NAMESERVER_ADDUINT32:
472             LOG1("LAD_NAMESERVER_ADDUINT32: calling NameServer_addUInt32(%p, ", cmd.args.addUInt32.handle)
473             LOG2("'%s', 0x%x)...\n", cmd.args.addUInt32.name, cmd.args.addUInt32.val)
475             rsp.entryPtr = NameServer_addUInt32(
476                 cmd.args.addUInt32.handle,
477                 cmd.args.addUInt32.name,
478                 cmd.args.addUInt32.val);
480             LOG1("    entryPtr = %p\n", rsp.entryPtr)
481             LOG0("DONE\n")
483             break;
485           case LAD_NAMESERVER_GETUINT32:
486             LOG2("LAD_NAMESERVER_GETUINT32: calling NameServer_getUInt32(%p, '%s')...\n", cmd.args.getUInt32.handle, cmd.args.getUInt32.name)
488             if (cmd.args.getUInt32.procId[0] == (UInt16)-1) {
489                 procIdPtr = NULL;
490             }
491             else {
492                 procIdPtr = cmd.args.getUInt32.procId;
493             }
494             rsp.status = NameServer_getUInt32(
495                 cmd.args.getUInt32.handle,
496                 cmd.args.getUInt32.name,
497                 &rsp.getUInt32.val,
498                 procIdPtr);
500             LOG1("    value = 0x%x\n", rsp.getUInt32.val)
501             LOG1("    status = %d\n", rsp.status)
502             LOG0("DONE\n")
504             break;
506           case LAD_NAMESERVER_GETLOCAL:
507             rsp.get.status = NameServer_getLocal(cmd.args.getLocal.handle,
508                 cmd.args.getLocal.name, &rsp.get.buf, &cmd.args.getLocal.len);
509             rsp.get.len = cmd.args.getLocal.len;
510             break;
512           case LAD_NAMESERVER_GETLOCALUINT32:
513             rsp.getUInt32.status = NameServer_getLocalUInt32(
514                 cmd.args.getLocalUInt32.handle,
515                 cmd.args.getLocalUInt32.name,
516                 &rsp.getUInt32.val);
517             break;
519           case LAD_NAMESERVER_REMOVE:
520             LOG2("LAD_NAMESERVER_REMOVE: calling NameServer_remove(%p, '%s')...\n", cmd.args.remove.handle, cmd.args.remove.name)
522             rsp.status = NameServer_remove(cmd.args.remove.handle,
523                                                cmd.args.remove.name);
525             LOG1("    status = %d\n", rsp.status)
526             LOG0("DONE\n")
528             break;
530           case LAD_NAMESERVER_REMOVEENTRY:
531             LOG2("LAD_NAMESERVER_REMOVEENTRY: calling NameServer_removeEntry(%p, %p)...\n", cmd.args.removeEntry.handle, cmd.args.removeEntry.entryPtr)
533             rsp.status = NameServer_removeEntry(
534                 cmd.args.removeEntry.handle,
535                 cmd.args.removeEntry.entryPtr);
537             LOG1("    status = %d\n", rsp.status)
538             LOG0("DONE\n")
540             break;
542           case LAD_NAMESERVER_ATTACH:
543             rsp.status = NameServer_attach(cmd.args.attach.procId);
544             break;
546           case LAD_NAMESERVER_DETACH:
547             rsp.status = NameServer_detach(cmd.args.detach.procId);
548             break;
550           case LAD_MESSAGEQ_GETCONFIG:
551             LOG0("LAD_MESSAGEQ_GETCONFIG: calling MessageQ_getConfig()...\n")
553             MessageQ_getConfig(&rsp.messageQGetConfig.cfg);
554             rsp.messageQGetConfig.status = 0;
556             LOG1("    status = %d\n", rsp.messageQGetConfig.status)
557             LOG0("DONE\n")
559             break;
561           case LAD_MESSAGEQ_SETUP:
562             LOG0("LAD_MESSAGEQ_SETUP: calling MessageQ_setup()...\n")
564             rsp.setup.status = MessageQ_setup(&cmd.args.messageQSetup.cfg);
565             rsp.setup.nameServerHandle = MessageQ_getNameServerHandle();
567             LOG1("    status = %d\n", rsp.setup.status)
568             LOG0("DONE\n")
570             break;
572           case LAD_MESSAGEQ_DESTROY:
573             LOG0("LAD_MESSAGEQ_DESTROY: calling MessageQ_destroy()...\n")
575             rsp.status = MessageQ_destroy();
577             LOG1("    status = %d\n", rsp.status)
578             LOG0("DONE\n")
580             break;
582           case LAD_MESSAGEQ_CREATE:
583             LOG2("LAD_MESSAGEQ_CREATE: calling MessageQ_create(%p, %p)...\n",
584                     cmd.args.messageQCreate.name,
585                     &cmd.args.messageQCreate.params);
587             tmpString = (cmd.args.messageQCreate.name[0] == '\0') ? NULL :
588                 cmd.args.messageQCreate.name;
590             handle = MessageQ_create(tmpString, &cmd.args.messageQCreate.params);
591             rsp.messageQCreate.serverHandle = handle;
593             if (handle) {
594                 rsp.messageQCreate.queueId = MessageQ_getQueueId(handle);
595                 MessageQ_setQueueOwner(handle, clientPID[clientId]);
596                 rsp.messageQCreate.status = 0;
597             }
598             else {
599                 rsp.messageQCreate.status = -1;
600             }
602             LOG1("    status = %d\n", rsp.messageQCreate.status)
603             LOG0("DONE\n")
605             break;
607           case LAD_MESSAGEQ_DELETE:
608             LOG1("LAD_MESSAGEQ_DELETE: calling MessageQ_delete(%p)...\n", cmd.args.messageQDelete.serverHandle)
610             rsp.messageQDelete.status =
611                 MessageQ_delete((MessageQ_Handle *)&cmd.args.messageQDelete.serverHandle);
613             LOG1("    status = %d\n", rsp.messageQDelete.status)
614             LOG0("DONE\n")
616             break;
618           case LAD_MESSAGEQ_MSGINIT:
619             LOG1("LAD_MESSAGEQ_MSGINIT: calling MessageQ_msgInit(%p)...\n", &rsp.msgInit.msg);
621             MessageQ_msgInit(&rsp.msgInit.msg);
622             rsp.msgInit.status = 0;
624             LOG1("    status = %d\n", rsp.msgInit.status)
625             LOG0("DONE\n")
627             break;
629           case LAD_MULTIPROC_GETCONFIG:
630             LOG0("LAD_MULTIPROC_GETCONFIG: calling MultiProc_getConfig()...\n")
632             MultiProc_getConfig(&rsp.multiprocGetConfig.cfg);
633             rsp.multiprocGetConfig.status = 0;
635             LOG1("    status = %d\n", rsp.multiprocGetConfig.status)
636             LOG0("DONE\n")
638             break;
640 #if defined(GATEMP_SUPPORT)
641           case LAD_GATEMP_START:
642             LOG0("LAD_GATEMP_START: calling GateMP_start()...\n")
644             rsp.gateMPStart.nameServerHandle = GateMP_getNameServer();
645             rsp.gateMPStart.status = GateMP_S_SUCCESS;;
647             LOG1("    status = %d\n", rsp.gateMPStart.status)
648             LOG0("DONE\n")
650             break;
652           case LAD_GATEMP_GETNUMRESOURCES:
653             LOG0("LAD_GATEMP_GETNUMRESOURCES: calling GateMP_getNumResources()...\n")
655             rsp.gateMPGetNumResources.value = GateMP_getNumResources(
656                                           cmd.args.gateMPGetNumResources.type);
657             rsp.gateMPGetNumResources.status = GateMP_S_SUCCESS;;
659             LOG1("    status = %d\n", rsp.gateMPGetNumResources.status)
660             LOG0("DONE\n")
662             break;
664           case LAD_GATEMP_GETFREERESOURCE:
665             LOG0("LAD_GATEMP_GETFREERESOURCE: calling GateMP_getFreeResource()...\n")
667             rsp.gateMPGetFreeResource.id = GateMP_getFreeResource(
668                                           cmd.args.gateMPGetFreeResource.type);
669             rsp.gateMPGetFreeResource.status = GateMP_S_SUCCESS;;
671             LOG1("    status = %d\n", rsp.gateMPGetFreeResource.status)
672             LOG0("DONE\n")
674             break;
676           case LAD_GATEMP_RELEASERESOURCE:
677             LOG0("LAD_GATEMP_RELEASERESOURCE: calling GateMP_releaseResource()...\n")
679             rsp.gateMPReleaseResource.status = GateMP_releaseResource(
680                                           cmd.args.gateMPReleaseResource.id,
681                                           cmd.args.gateMPReleaseResource.type);
683             LOG1("    status = %d\n", rsp.gateMPReleaseResource.status)
684             LOG0("DONE\n")
686             break;
688           case LAD_GATEMP_ISSETUP:
689             LOG0("LAD_GATEMP_ISSETUP: calling GateMP_isSetup()...\n")
691             rsp.gateMPIsSetup.result = GateMP_isSetup();
692             rsp.gateMPIsSetup.status = GateMP_S_SUCCESS;
694             LOG1("    status = %d\n", rsp.gateMPIsSetup.status)
695             LOG0("DONE\n")
697             break;
699           case LAD_GATEHWSPINLOCK_GETCONFIG:
700             LOG0("LAD_GATEHWSPINLOCK_GETCONFIG: calling GateHWSpinlock_getConfig()...\n")
702             GateHWSpinlock_getConfig(&rsp.gateHWSpinlockGetConfig.cfgParams);
703             rsp.gateHWSpinlockGetConfig.status = 0;
705             LOG1("    status = %d\n", rsp.gateHWSpinlockGetConfig.status)
706             LOG0("DONE\n")
708             break;
709 #endif
711           case LAD_EXIT:
712             goto exitNow;
714             break;
716           default:
717             LOG1("\nUnrecognized command: 0x%x\n", command)
719             break;
720         }
722         switch (command) {
723           case LAD_CONNECT:
724           case LAD_DISCONNECT:
725             break;
727           case LAD_IPC_GETCONFIG:
728           case LAD_NAMESERVER_SETUP:
729           case LAD_NAMESERVER_DESTROY:
730           case LAD_NAMESERVER_PARAMS_INIT:
731           case LAD_NAMESERVER_CREATE:
732           case LAD_NAMESERVER_DELETE:
733           case LAD_NAMESERVER_ADD:
734           case LAD_NAMESERVER_GET:
735           case LAD_NAMESERVER_ADDUINT32:
736           case LAD_NAMESERVER_GETUINT32:
737           case LAD_NAMESERVER_GETLOCAL:
738           case LAD_NAMESERVER_GETLOCALUINT32:
739           case LAD_NAMESERVER_REMOVE:
740           case LAD_NAMESERVER_REMOVEENTRY:
741           case LAD_NAMESERVER_ATTACH:
742           case LAD_NAMESERVER_DETACH:
743           case LAD_MESSAGEQ_GETCONFIG:
744           case LAD_MESSAGEQ_SETUP:
745           case LAD_MESSAGEQ_DESTROY:
746           case LAD_MESSAGEQ_CREATE:
747           case LAD_MESSAGEQ_DELETE:
748           case LAD_MESSAGEQ_MSGINIT:
749           case LAD_MULTIPROC_GETCONFIG:
750 #if defined(GATEMP_SUPPORT)
751           case LAD_GATEMP_START:
752           case LAD_GATEMP_GETNUMRESOURCES:
753           case LAD_GATEMP_GETFREERESOURCE:
754           case LAD_GATEMP_RELEASERESOURCE:
755           case LAD_GATEMP_ISSETUP:
756           case LAD_GATEHWSPINLOCK_GETCONFIG:
757 #endif
759             LOG0("Sending response...\n");
761             fwrite(&rsp, LAD_RESPONSELENGTH, 1, responseFIFOFilePtr[clientId]);
762             fflush(responseFIFOFilePtr[clientId]);
764             break;
766           default:
767             break;
768         }
769     }
771 exitNow:
772 #if defined(GATEMP_SUPPORT)
773     if (gatempEnabled) {
774         GateMP_destroy();
775         NameServer_destroy();
776     }
777 #endif
778     if (logFile) {
779         LOG0("\n\nLAD IS SELF TERMINATING...\n\n")
780         fclose(logPtr);
781     }
782     unlink(commandFIFOFile);
784     return(0);
789 /*
790  *  ======== assignClientId ========
791  */
792 static LAD_ClientHandle assignClientId(Void)
794     Int clientId = -1;
795     Int i;
797     /* scan connection status flags to acquire a clientId */
798     for (i = 0; i < LAD_MAXNUMCLIENTS; i++) {
799         /* if slot open then provisionally select this clientId */
800         if (clientConnected[i] == FALSE) {
801              clientId = i;
802              break;
803         }
804     }
806     return(clientId);
810 /*
811  *  ======== cleanupDepartedClients ========
812  */
813 static Void cleanupDepartedClients(Void)
815     Int killStat;
816     Int i;
818     /* scan all connections to verify client processes still exist... */
819     for (i = 0; i < LAD_MAXNUMCLIENTS; i++) {
821         /* if connected... */
822         if (clientConnected[i] == TRUE) {
824             /* check if the client process (PID) still exists */
825             /*
826              * NOTE - calling kill with signal value of 0 will perform
827              * error checking, but not actually send a signal.  Will use this
828              * error check to see if PID still exists.  An alternative was
829              * to call getpgid.  This worked, but is apparently limited to
830              * USE_XOPEN_EXTENDED configurations.
831              */
832             killStat = kill(clientPID[i], 0);
833             if ((killStat == -1) && (errno == ESRCH)) {
835                 LOG1("\nDETECTED CONNECTED CLIENT #%d HAS DEPARTED!", i)
837                 /* will always need to do the disconnect... */
838                 LOG0("\nDoing DISCONNECT on behalf of client...")
839                 doDisconnect(i);
841                 MessageQ_cleanupOwner(clientPID[i]);
842 //                NameServer_cleanupOwner(clientPID[i]);
844                 LOG0("DONE\n")
845             }
846         }
847     }
851 /*
852  *  ======== connectToLAD ========
853  */
854 static Int connectToLAD(String clientName, Int pid, String clientProto, Int *clientIdPtr)
856     Int clientId = -1;
857     Bool connectDenied = FALSE;
858     Int status = LAD_SUCCESS;
859     FILE * filePtr;
860     Int statusIO;
862     /*
863      * TODO:L here, and everywhere parse FIFO strings: should
864      * add full error checking for incomplete or corrupted
865      * strings? Since LAD to ladclient comms are "closed", and
866      * tested, the likelihood of problems seems very low.
867      * But should still consider doing full error checking
868      * and, hopefully, recovery.
869      */
870     LOG0("\nLAD_CONNECT: \n")
871     LOG1("    client FIFO name = %s\n", clientName)
872     LOG1("    client PID = %d\n", pid)
874     /* first check for proper communication protocol */
875     if (strcmp(clientProto, LAD_PROTOCOLVERSION) != 0) {
877         /* if no match then reject the request */
878         LOG0("    ERROR: mismatch in communication protocol!\n")
879         LOG1("        LAD protocol = %s\n", LAD_PROTOCOLVERSION)
880         LOG1("        client protocol = %s\n", clientProto)
881         status = LAD_INVALIDVERSION;
883         /* set flag so know to close FIFO after response */
884         connectDenied = TRUE;
886         /* now jump forward a bit to send response */
887         goto openResponseFIFO;
888     }
890     /* determine this client's ID */
891     clientId = assignClientId();
893     /* if failed to acquire an ID then exit early */
894     if (clientId == -1) {
895         LOG0("    no free handle; too many connections!\n")
896         status = LAD_ACCESSDENIED;
898         /* set flag so know to close FIFO after response */
899         connectDenied = TRUE;
900     }
901     else {
902         LOG1("    assigned client handle = %d\n", clientId)
904         /* save the client's FIFO name for when disconnect */
905         strcpy(clientFIFOName[clientId], clientName);
906     }
908 openResponseFIFO:
910     /* if response FIFO exists from previous LAD session delete it now */
911     unlink(clientName);
913     /* create the dedicated response FIFO to the client */
914     statusIO = mkfifo(clientName, 0777);
915     if (statusIO != 0) {
917         LOG2("\nERROR: unable to mkfifo %s, errno = %x\n", clientName, errno)
919         status = LAD_IOFAILURE;
921         /* send no response; connection request will timeout */
922         goto doneconnect;
923     }
925     LOG1("    FIFO %s created\n", clientName)
927     /* set FIFO permissions to read/write */
928     chmod(clientName, 0666);
930     filePtr = fopen(clientName, "w");
931     if (filePtr == NULL) {
932         LOG1("\nERROR: unable to open response FIFO %s\n", clientName)
934         /* if failed open, still need to delete the FIFO */
935         unlink(clientName);
937         status = LAD_IOFAILURE;
939         /* send no response; connection request will timeout */
940         goto doneconnect;
941     }
943     LOG1("    FIFO %s opened for writing\n", clientName)
945     /*
946      * set "this client is connected" flag; this client ID is now "owned", and
947      * is no longer provisional
948      */
949     if (connectDenied == FALSE) {
950         responseFIFOFilePtr[clientId] = filePtr;
951         clientPID[clientId] = pid;
952         clientConnected[clientId] = TRUE;
953     }
955     rsp.connect.assignedId = clientId;
956     rsp.status = status;
958     /* put response to FIFO */
959     fwrite(&rsp, LAD_RESPONSELENGTH, 1, filePtr);
960     fflush(filePtr);
962     LOG0("    sent response\n")
964     /* if connection was denied, must now close FIFO */
965     if (connectDenied == TRUE) {
966         LOG1("    connect denied; closing FIFO %s\n", clientName)
967         fclose(filePtr);
968         unlink(clientName);
969     }
971     LOG0("DONE\n")
973 doneconnect:
974     if (clientIdPtr != NULL) {
975         *clientIdPtr = clientId;
976     }
978     return(status);
982 /*
983  *  ======== disconnectFromLAD ========
984  */
985 static Void disconnectFromLAD(Int clientId)
987     LOG0("\nLAD_DISCONNECT: ")
989     LOG1("\n    client handle = %x", clientId)
990     doDisconnect(clientId);
992     LOG0("DONE\n")
994     return;
998 /*
999  *  ======== doDisconnect ========
1000  */
1001 static Void doDisconnect(Int clientId)
1003     /* set "this client is not connected" flag */
1004     clientConnected[clientId] = FALSE;
1006     /* close and remove the response FIFO */
1007     LOG2("\n    closing FIFO %s (filePtr=%p)\n",
1008         clientFIFOName[clientId], responseFIFOFilePtr[clientId])
1009     fclose(responseFIFOFilePtr[clientId]);
1011     LOG1("    done, unlinking %s\n", clientFIFOName[clientId]);
1012     unlink(clientFIFOName[clientId]);