Linux: Added option to set base cluster id in LAD
[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_NAMESERVER_SETUP:
376             LOG0("LAD_NAMESERVER_SETUP: calling NameServer_setup()...\n")
378             rsp.status = NameServer_setup();
380             LOG1("    status = %d\n", rsp.status)
381             LOG0("DONE\n")
383             break;
385           case LAD_NAMESERVER_DESTROY:
386             LOG0("LAD_NAMESERVER_DESTROY: calling NameServer_destroy()...\n")
388             rsp.status = NameServer_destroy();
390             LOG1("    status = %d\n", rsp.status)
391             LOG0("DONE\n")
393             break;
395           case LAD_NAMESERVER_PARAMS_INIT:
396             LOG0("LAD_NAMESERVER_PARAMS_INIT: calling NameServer_Params_init()...\n")
398             NameServer_Params_init(&rsp.params);
400             LOG0("DONE\n")
402             break;
404           case LAD_NAMESERVER_CREATE:
405             LOG1("LAD_NAMESERVER_CREATE: calling NameServer_create('%s')...\n", cmd.args.create.name)
407             rsp.handle = NameServer_create(cmd.args.create.name,
408                                                &cmd.args.create.params);
410             LOG1("    handle = %p\n", rsp.handle)
411             LOG0("DONE\n")
413             break;
415           case LAD_NAMESERVER_DELETE:
416             LOG1("LAD_NAMESERVER_DELETE: calling NameServer_delete(%p)...\n", cmd.args.delete.handle)
418             rsp.delete.handle = cmd.args.delete.handle;
419             rsp.delete.status = NameServer_delete(&rsp.delete.handle);
421             LOG1("    status = %d\n", rsp.status)
422             LOG0("DONE\n")
424             break;
426           case LAD_NAMESERVER_ADD:
427             LOG1("LAD_NAMESERVER_ADD: calling NameServer_add(%p, ", cmd.args.add.handle)
428             LOG2("'%s', %p,", cmd.args.add.name, cmd.args.add.buf)
429             LOG1(" 0x%x)...\n", cmd.args.add.len)
431             rsp.entryPtr = NameServer_add(
432                 cmd.args.add.handle,
433                 cmd.args.add.name,
434                 cmd.args.add.buf,
435                 cmd.args.add.len);
437             LOG1("    entryPtr = %p\n", rsp.entryPtr)
438             LOG0("DONE\n")
440             break;
442           case LAD_NAMESERVER_GET:
443             LOG2("LAD_NAMESERVER_GET: calling NameServer_get(%p, '%s'",
444                 cmd.args.get.handle, cmd.args.get.name)
445             LOG0(")...\n")
447             if (cmd.args.get.procId[0] == (UInt16)-1) {
448                 procIdPtr = NULL;
449             }
450             else {
451                 procIdPtr = cmd.args.get.procId;
452             }
453             rsp.status = NameServer_get(
454                 cmd.args.get.handle,
455                 cmd.args.get.name,
456                 rsp.get.buf,
457                 &cmd.args.get.len,
458                 procIdPtr);
459             rsp.get.len = cmd.args.get.len;
461             LOG1("    value = 0x%x\n", rsp.get.len)
462             LOG1("    status = %d\n", rsp.status)
463             LOG0("DONE\n")
465             break;
467           case LAD_NAMESERVER_ADDUINT32:
468             LOG1("LAD_NAMESERVER_ADDUINT32: calling NameServer_addUInt32(%p, ", cmd.args.addUInt32.handle)
469             LOG2("'%s', 0x%x)...\n", cmd.args.addUInt32.name, cmd.args.addUInt32.val)
471             rsp.entryPtr = NameServer_addUInt32(
472                 cmd.args.addUInt32.handle,
473                 cmd.args.addUInt32.name,
474                 cmd.args.addUInt32.val);
476             LOG1("    entryPtr = %p\n", rsp.entryPtr)
477             LOG0("DONE\n")
479             break;
481           case LAD_NAMESERVER_GETUINT32:
482             LOG2("LAD_NAMESERVER_GETUINT32: calling NameServer_getUInt32(%p, '%s')...\n", cmd.args.getUInt32.handle, cmd.args.getUInt32.name)
484             if (cmd.args.getUInt32.procId[0] == (UInt16)-1) {
485                 procIdPtr = NULL;
486             }
487             else {
488                 procIdPtr = cmd.args.getUInt32.procId;
489             }
490             rsp.status = NameServer_getUInt32(
491                 cmd.args.getUInt32.handle,
492                 cmd.args.getUInt32.name,
493                 &rsp.getUInt32.val,
494                 procIdPtr);
496             LOG1("    value = 0x%x\n", rsp.getUInt32.val)
497             LOG1("    status = %d\n", rsp.status)
498             LOG0("DONE\n")
500             break;
502           case LAD_NAMESERVER_REMOVE:
503             LOG2("LAD_NAMESERVER_REMOVE: calling NameServer_remove(%p, '%s')...\n", cmd.args.remove.handle, cmd.args.remove.name)
505             rsp.status = NameServer_remove(cmd.args.remove.handle,
506                                                cmd.args.remove.name);
508             LOG1("    status = %d\n", rsp.status)
509             LOG0("DONE\n")
511             break;
513           case LAD_NAMESERVER_REMOVEENTRY:
514             LOG2("LAD_NAMESERVER_REMOVEENTRY: calling NameServer_removeEntry(%p, %p)...\n", cmd.args.removeEntry.handle, cmd.args.removeEntry.entryPtr)
516             rsp.status = NameServer_removeEntry(
517                 cmd.args.removeEntry.handle,
518                 cmd.args.removeEntry.entryPtr);
520             LOG1("    status = %d\n", rsp.status)
521             LOG0("DONE\n")
523             break;
525           case LAD_MESSAGEQ_GETCONFIG:
526             LOG0("LAD_MESSAGEQ_GETCONFIG: calling MessageQ_getConfig()...\n")
528             MessageQ_getConfig(&rsp.messageQGetConfig.cfg);
529             rsp.messageQGetConfig.status = 0;
531             LOG1("    status = %d\n", rsp.messageQGetConfig.status)
532             LOG0("DONE\n")
534             break;
536           case LAD_MESSAGEQ_SETUP:
537             LOG0("LAD_MESSAGEQ_SETUP: calling MessageQ_setup()...\n")
539             rsp.setup.status = MessageQ_setup(&cmd.args.messageQSetup.cfg);
540             rsp.setup.nameServerHandle = MessageQ_getNameServerHandle();
542             LOG1("    status = %d\n", rsp.setup.status)
543             LOG0("DONE\n")
545             break;
547           case LAD_MESSAGEQ_DESTROY:
548             LOG0("LAD_MESSAGEQ_DESTROY: calling MessageQ_destroy()...\n")
550             rsp.status = MessageQ_destroy();
552             LOG1("    status = %d\n", rsp.status)
553             LOG0("DONE\n")
555             break;
557           case LAD_MESSAGEQ_CREATE:
558             LOG2("LAD_MESSAGEQ_CREATE: calling MessageQ_create(%p, %p)...\n",
559                     cmd.args.messageQCreate.name,
560                     &cmd.args.messageQCreate.params);
562             tmpString = (cmd.args.messageQCreate.name[0] == '\0') ? NULL :
563                 cmd.args.messageQCreate.name;
565             handle = MessageQ_create(tmpString, &cmd.args.messageQCreate.params);
566             rsp.messageQCreate.serverHandle = handle;
568             if (handle) {
569                 rsp.messageQCreate.queueId = MessageQ_getQueueId(handle);
570                 MessageQ_setQueueOwner(handle, clientPID[clientId]);
571                 rsp.messageQCreate.status = 0;
572             }
573             else {
574                 rsp.messageQCreate.status = -1;
575             }
577             LOG1("    status = %d\n", rsp.messageQCreate.status)
578             LOG0("DONE\n")
580             break;
582           case LAD_MESSAGEQ_DELETE:
583             LOG1("LAD_MESSAGEQ_DELETE: calling MessageQ_delete(%p)...\n", cmd.args.messageQDelete.serverHandle)
585             rsp.messageQDelete.status =
586                 MessageQ_delete((MessageQ_Handle *)&cmd.args.messageQDelete.serverHandle);
588             LOG1("    status = %d\n", rsp.messageQDelete.status)
589             LOG0("DONE\n")
591             break;
593           case LAD_MESSAGEQ_MSGINIT:
594             LOG1("LAD_MESSAGEQ_MSGINIT: calling MessageQ_msgInit(%p)...\n", &rsp.msgInit.msg);
596             MessageQ_msgInit(&rsp.msgInit.msg);
597             rsp.msgInit.status = 0;
599             LOG1("    status = %d\n", rsp.msgInit.status)
600             LOG0("DONE\n")
602             break;
604           case LAD_MULTIPROC_GETCONFIG:
605             LOG0("LAD_MULTIPROC_GETCONFIG: calling MultiProc_getConfig()...\n")
607             MultiProc_getConfig(&rsp.multiprocGetConfig.cfg);
608             rsp.multiprocGetConfig.status = 0;
610             LOG1("    status = %d\n", rsp.multiprocGetConfig.status)
611             LOG0("DONE\n")
613             break;
615 #if defined(GATEMP_SUPPORT)
616           case LAD_GATEMP_START:
617             LOG0("LAD_GATEMP_START: calling GateMP_start()...\n")
619             rsp.gateMPStart.nameServerHandle = GateMP_getNameServer();
620             rsp.gateMPStart.status = GateMP_S_SUCCESS;;
622             LOG1("    status = %d\n", rsp.gateMPStart.status)
623             LOG0("DONE\n")
625             break;
627           case LAD_GATEMP_GETNUMRESOURCES:
628             LOG0("LAD_GATEMP_GETNUMRESOURCES: calling GateMP_getNumResources()...\n")
630             rsp.gateMPGetNumResources.value = GateMP_getNumResources(
631                                           cmd.args.gateMPGetNumResources.type);
632             rsp.gateMPGetNumResources.status = GateMP_S_SUCCESS;;
634             LOG1("    status = %d\n", rsp.gateMPGetNumResources.status)
635             LOG0("DONE\n")
637             break;
639           case LAD_GATEMP_GETFREERESOURCE:
640             LOG0("LAD_GATEMP_GETFREERESOURCE: calling GateMP_getFreeResource()...\n")
642             rsp.gateMPGetFreeResource.id = GateMP_getFreeResource(
643                                           cmd.args.gateMPGetFreeResource.type);
644             rsp.gateMPGetFreeResource.status = GateMP_S_SUCCESS;;
646             LOG1("    status = %d\n", rsp.gateMPGetFreeResource.status)
647             LOG0("DONE\n")
649             break;
651           case LAD_GATEMP_RELEASERESOURCE:
652             LOG0("LAD_GATEMP_RELEASERESOURCE: calling GateMP_releaseResource()...\n")
654             rsp.gateMPReleaseResource.status = GateMP_releaseResource(
655                                           cmd.args.gateMPReleaseResource.id,
656                                           cmd.args.gateMPReleaseResource.type);
658             LOG1("    status = %d\n", rsp.gateMPReleaseResource.status)
659             LOG0("DONE\n")
661             break;
663           case LAD_GATEMP_ISSETUP:
664             LOG0("LAD_GATEMP_ISSETUP: calling GateMP_isSetup()...\n")
666             rsp.gateMPIsSetup.result = GateMP_isSetup();
667             rsp.gateMPIsSetup.status = GateMP_S_SUCCESS;
669             LOG1("    status = %d\n", rsp.gateMPIsSetup.status)
670             LOG0("DONE\n")
672             break;
674           case LAD_GATEHWSPINLOCK_GETCONFIG:
675             LOG0("LAD_GATEHWSPINLOCK_GETCONFIG: calling GateHWSpinlock_getConfig()...\n")
677             GateHWSpinlock_getConfig(&rsp.gateHWSpinlockGetConfig.cfgParams);
678             rsp.gateHWSpinlockGetConfig.status = 0;
680             LOG1("    status = %d\n", rsp.gateHWSpinlockGetConfig.status)
681             LOG0("DONE\n")
683             break;
684 #endif
686           case LAD_EXIT:
687             goto exitNow;
689             break;
691           default:
692             LOG1("\nUnrecognized command: 0x%x\n", command)
694             break;
695         }
697         switch (command) {
698           case LAD_CONNECT:
699           case LAD_DISCONNECT:
700             break;
702           case LAD_NAMESERVER_SETUP:
703           case LAD_NAMESERVER_DESTROY:
704           case LAD_NAMESERVER_PARAMS_INIT:
705           case LAD_NAMESERVER_CREATE:
706           case LAD_NAMESERVER_DELETE:
707           case LAD_NAMESERVER_ADD:
708           case LAD_NAMESERVER_GET:
709           case LAD_NAMESERVER_ADDUINT32:
710           case LAD_NAMESERVER_GETUINT32:
711           case LAD_NAMESERVER_REMOVE:
712           case LAD_NAMESERVER_REMOVEENTRY:
713           case LAD_MESSAGEQ_GETCONFIG:
714           case LAD_MESSAGEQ_SETUP:
715           case LAD_MESSAGEQ_DESTROY:
716           case LAD_MESSAGEQ_CREATE:
717           case LAD_MESSAGEQ_DELETE:
718           case LAD_MESSAGEQ_MSGINIT:
719           case LAD_MULTIPROC_GETCONFIG:
720 #if defined(GATEMP_SUPPORT)
721           case LAD_GATEMP_START:
722           case LAD_GATEMP_GETNUMRESOURCES:
723           case LAD_GATEMP_GETFREERESOURCE:
724           case LAD_GATEMP_RELEASERESOURCE:
725           case LAD_GATEMP_ISSETUP:
726           case LAD_GATEHWSPINLOCK_GETCONFIG:
727 #endif
729             LOG0("Sending response...\n");
731             fwrite(&rsp, LAD_RESPONSELENGTH, 1, responseFIFOFilePtr[clientId]);
732             fflush(responseFIFOFilePtr[clientId]);
734             break;
736           default:
737             break;
738         }
739     }
741 exitNow:
742 #if defined(GATEMP_SUPPORT)
743     if (gatempEnabled) {
744         GateMP_destroy();
745         NameServer_destroy();
746     }
747 #endif
748     if (logFile) {
749         LOG0("\n\nLAD IS SELF TERMINATING...\n\n")
750         fclose(logPtr);
751     }
752     unlink(commandFIFOFile);
754     return(0);
759 /*
760  *  ======== assignClientId ========
761  */
762 static LAD_ClientHandle assignClientId(Void)
764     Int clientId = -1;
765     Int i;
767     /* scan connection status flags to acquire a clientId */
768     for (i = 0; i < LAD_MAXNUMCLIENTS; i++) {
769         /* if slot open then provisionally select this clientId */
770         if (clientConnected[i] == FALSE) {
771              clientId = i;
772              break;
773         }
774     }
776     return(clientId);
780 /*
781  *  ======== cleanupDepartedClients ========
782  */
783 static Void cleanupDepartedClients(Void)
785     Int killStat;
786     Int i;
788     /* scan all connections to verify client processes still exist... */
789     for (i = 0; i < LAD_MAXNUMCLIENTS; i++) {
791         /* if connected... */
792         if (clientConnected[i] == TRUE) {
794             /* check if the client process (PID) still exists */
795             /*
796              * NOTE - calling kill with signal value of 0 will perform
797              * error checking, but not actually send a signal.  Will use this
798              * error check to see if PID still exists.  An alternative was
799              * to call getpgid.  This worked, but is apparently limited to
800              * USE_XOPEN_EXTENDED configurations.
801              */
802             killStat = kill(clientPID[i], 0);
803             if ((killStat == -1) && (errno == ESRCH)) {
805                 LOG1("\nDETECTED CONNECTED CLIENT #%d HAS DEPARTED!", i)
807                 /* will always need to do the disconnect... */
808                 LOG0("\nDoing DISCONNECT on behalf of client...")
809                 doDisconnect(i);
811                 MessageQ_cleanupOwner(clientPID[i]);
812 //                NameServer_cleanupOwner(clientPID[i]);
814                 LOG0("DONE\n")
815             }
816         }
817     }
821 /*
822  *  ======== connectToLAD ========
823  */
824 static Int connectToLAD(String clientName, Int pid, String clientProto, Int *clientIdPtr)
826     Int clientId = -1;
827     Bool connectDenied = FALSE;
828     Int status = LAD_SUCCESS;
829     FILE * filePtr;
830     Int statusIO;
832     /*
833      * TODO:L here, and everywhere parse FIFO strings: should
834      * add full error checking for incomplete or corrupted
835      * strings? Since LAD to ladclient comms are "closed", and
836      * tested, the likelihood of problems seems very low.
837      * But should still consider doing full error checking
838      * and, hopefully, recovery.
839      */
840     LOG0("\nLAD_CONNECT: \n")
841     LOG1("    client FIFO name = %s\n", clientName)
842     LOG1("    client PID = %d\n", pid)
844     /* first check for proper communication protocol */
845     if (strcmp(clientProto, LAD_PROTOCOLVERSION) != 0) {
847         /* if no match then reject the request */
848         LOG0("    ERROR: mismatch in communication protocol!\n")
849         LOG1("        LAD protocol = %s\n", LAD_PROTOCOLVERSION)
850         LOG1("        client protocol = %s\n", clientProto)
851         status = LAD_INVALIDVERSION;
853         /* set flag so know to close FIFO after response */
854         connectDenied = TRUE;
856         /* now jump forward a bit to send response */
857         goto openResponseFIFO;
858     }
860     /* determine this client's ID */
861     clientId = assignClientId();
863     /* if failed to acquire an ID then exit early */
864     if (clientId == -1) {
865         LOG0("    no free handle; too many connections!\n")
866         status = LAD_ACCESSDENIED;
868         /* set flag so know to close FIFO after response */
869         connectDenied = TRUE;
870     }
871     else {
872         LOG1("    assigned client handle = %d\n", clientId)
874         /* save the client's FIFO name for when disconnect */
875         strcpy(clientFIFOName[clientId], clientName);
876     }
878 openResponseFIFO:
880     /* if response FIFO exists from previous LAD session delete it now */
881     unlink(clientName);
883     /* create the dedicated response FIFO to the client */
884     statusIO = mkfifo(clientName, 0777);
885     if (statusIO != 0) {
887         LOG2("\nERROR: unable to mkfifo %s, errno = %x\n", clientName, errno)
889         status = LAD_IOFAILURE;
891         /* send no response; connection request will timeout */
892         goto doneconnect;
893     }
895     LOG1("    FIFO %s created\n", clientName)
897     /* set FIFO permissions to read/write */
898     chmod(clientName, 0666);
900     filePtr = fopen(clientName, "w");
901     if (filePtr == NULL) {
902         LOG1("\nERROR: unable to open response FIFO %s\n", clientName)
904         /* if failed open, still need to delete the FIFO */
905         unlink(clientName);
907         status = LAD_IOFAILURE;
909         /* send no response; connection request will timeout */
910         goto doneconnect;
911     }
913     LOG1("    FIFO %s opened for writing\n", clientName)
915     /*
916      * set "this client is connected" flag; this client ID is now "owned", and
917      * is no longer provisional
918      */
919     if (connectDenied == FALSE) {
920         responseFIFOFilePtr[clientId] = filePtr;
921         clientPID[clientId] = pid;
922         clientConnected[clientId] = TRUE;
923     }
925     rsp.connect.assignedId = clientId;
926     rsp.status = status;
928     /* put response to FIFO */
929     fwrite(&rsp, LAD_RESPONSELENGTH, 1, filePtr);
930     fflush(filePtr);
932     LOG0("    sent response\n")
934     /* if connection was denied, must now close FIFO */
935     if (connectDenied == TRUE) {
936         LOG1("    connect denied; closing FIFO %s\n", clientName)
937         fclose(filePtr);
938         unlink(clientName);
939     }
941     LOG0("DONE\n")
943 doneconnect:
944     if (clientIdPtr != NULL) {
945         *clientIdPtr = clientId;
946     }
948     return(status);
952 /*
953  *  ======== disconnectFromLAD ========
954  */
955 static Void disconnectFromLAD(Int clientId)
957     LOG0("\nLAD_DISCONNECT: ")
959     LOG1("\n    client handle = %x", clientId)
960     doDisconnect(clientId);
962     LOG0("DONE\n")
964     return;
968 /*
969  *  ======== doDisconnect ========
970  */
971 static Void doDisconnect(Int clientId)
973     /* set "this client is not connected" flag */
974     clientConnected[clientId] = FALSE;
976     /* close and remove the response FIFO */
977     LOG2("\n    closing FIFO %s (filePtr=%p)\n",
978         clientFIFOName[clientId], responseFIFOFilePtr[clientId])
979     fclose(responseFIFOFilePtr[clientId]);
981     LOG1("    done, unlinking %s\n", clientFIFOName[clientId]);
982     unlink(clientFIFOName[clientId]);