dispatch.c 13.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
/*
 * dispatch.c: select loop 
 *
 * Copyright 1995, Silicon Graphics, Inc.
 * All Rights Reserved.
 *
 * This is UNPUBLISHED PROPRIETARY SOURCE CODE of Silicon Graphics, Inc.;
 * the contents of this file may not be disclosed to third parties, copied or
 * duplicated in any form, in whole or in part, without the prior written
 * permission of Silicon Graphics, Inc.
 *
 * RESTRICTED RIGHTS LEGEND:
 * Use, duplication or disclosure by the Government is subject to restrictions
 * as set forth in subdivision (c)(1)(ii) of the Rights in Technical Data
 * and Computer Software clause at DFARS 252.227-7013, and/or in similar or
 * successor clauses in the FAR, DOD or NASA FAR Supplement. Unpublished -
 * rights reserved under the Copyright Laws of the United States.
 *
 * $Revision: 1.1.1.1 $
 */

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <mutex.h>
#include <string.h>
#include <bstring.h>
#include <alloca.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>

/*
 * includes needed for socket stuff
 */
#include <sys/un.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>


#include "driverd.h"
#include "utils.h"
#include "sys/u64gio.h"
#include "os.h"
#include "em.h"
#include "ramrom.h"


char isItTimeToYield;
unsigned long dispatchException = 0;

extern int MaxClients;
extern int currentMaxClients;

extern int numListeningSockets;
extern uint ListeningSockets[];

extern fd_set SelectReturnMask;	/* select returns available fd's in this set */

extern ClientPtr *clients;
extern int nextFreeClientID;	/* always MIN free client ID */
       int nClients;		/* number of active clients */
extern int verbose_flag;

#define MAX_REQUEST_SIZE 65535

static int ANYSET(fd_set * const);
static int eventfdlist[64];	    /* assume that 0 is not a socket fd */
static ClientPtr EmulatorClient;
static int shmkey;
void *shmaddr;		/* for emulator I/F, the address of shared memory */
static char writebuffer[8192];

/*
 * EstablishNewConnection():
 *
 * If anyone is waiting on the well known socket, accept them.
 * Returns a mask with indices of new clients.  Updates AllSockets
 * to include the new socket connection.
 */
int
EstablishNewConnection(void *closure)
{
    int socket;		/* fd of listener that's ready */
    int newconn;	/* fd of new client */
    int i;
    ClientPtr client;

    union {
	struct sockaddr sa;
	struct sockaddr_un un;
	struct sockaddr_in in;
    } from;

    int	fromlen;

    socket = *(int *)closure;

    if ((newconn = accept(socket, NULL, NULL)) < 0) 
	return 0;

    fromlen = sizeof(from);
    if (!getpeername(newconn, &from.sa, &fromlen)) {
	if (fromlen && (from.sa.sa_family == AF_INET)) {
	    int mi = 1;
	    setsockopt(newconn, IPPROTO_TCP, TCP_NODELAY,
		       (char *)&mi, sizeof(int));
	}
    }

/*(void) fcntl(newconn, F_SETFL, O_NONBLOCK);*/

    if (AddNewClient(newconn) < 0) {
	fprintf(stderr, "Driverd: Unable to add new client\n");
	close(newconn);
	return 0;
    }

    return 1;
}

/*
 * Transcribe info from the client which will be of use later when processing
 * commands.
 */
void RegisterClient(ClientPtr client, registerSessionPtr pData)
{
    int reply;
    
    client->id = pData->id;	/* PID (to be used when signalling emulator) */
    if (EmulatorClient) {
	reply = 1;
	Trace("Register Client OK\n");
    } else {
	reply = 0;
	Trace("Register Client no emulator yet\n");
    }
    write(client->fd, &reply, sizeof(reply));
    if (verbose_flag)
	fprintf(stderr, "Driverd: Register client %d\n", client->id);
}

void RegisterEmulatorClient(ClientPtr client, RegisterEmulator *pData)
{
    int sid;
    
    client->id = pData->id;	/* PID (to be used when signalling emulator) */
    EmulatorClient = client;
    shmkey = pData->shmkey;

    sid = shmget(shmkey, RAMROM_MSG_SIZE, IPC_CREAT | 0600);
    if (sid == -1)
    {
	perror("Error getting shm ID");
	exit(1);
    }
    shmaddr = shmat(sid, 0, 0);
    if ((int)shmaddr == -1)
    {
	perror("RegisterEmulatorClient Error getting shm addr");
	exit(1);
    }

    if (verbose_flag)
	fprintf(stderr, "Driverd: Register Emulator %d\n", client->id);
}

/*
 * Read an event from the game & dispatch to interested clients via writes on
 * their sockets.
 */
void ProcessEventFromGame(ClientPtr client, eventFromGamePtr pData)
{
    char event;
    int numWritten;

    event = pData->event;

    if (verbose_flag)
	fprintf(stderr, "Driverd: Event from Game %d\n", event);
#ifdef DEBUG
    fprintf(stderr, "Driverd: Received event %d; attempting to dispatch...\n", event);
#endif

    if (event < 0 || event > 63) {
	fprintf(stderr, "Driverd: ProcessEventFromGame: event out of range %d\n", event);
    }
    if (eventfdlist[event] > 0) {
	 numWritten = write(eventfdlist[event], &event, sizeof(event));
	     if (numWritten != sizeof(event)) {
		 fprintf(stderr, "Driverd: Bad write to %d (passing event 0x%x)\n", 
		     eventfdlist[event], event);
	     }
    } else {
	fprintf(stderr, "Driverd: ProcessEventFromGame: no one interested in %d queue it\n",
	    event);
	eventfdlist[event] = -1;
    }
}

/*
 * SendCommandToGame():
 *
 * daemon receives commands from host side clients, 
 * arbitrates for control of ramrom, writes the command into ramrom, 
 * sends a signal to the game to tell it to read the ramrom arena, then
 * waits for an acknowledge to come back from the game indicating that the
 * command has been accepted (so that the daemon could begin a new command
 * arbitration if needed).
 * 
void SendCommandToGame(ClientPtr client, commandToGamePtr pData)
{
}
 */

/* XXX what happens if client goes away in middle? */
int
readn(int fd, void *buf, int nbytes)
{
    unsigned char *bp;
    int n, ret;
    
    ret = nbytes;
    while (nbytes) {
	n = read(fd, buf, nbytes);
	if (n < 0) {
printf("readn failure fd %d, n is %d\n", fd, n);
perror("XXX");
	    return n;
	}
	buf = (void *)((int)buf + n);
	nbytes -= n;
    }
    return ret;
}

/*
 * Note that the last 8 bytes of the shared memory special are used
 * to pass the GIOinterrupt value, and what to copy to RAMROM
 */
void
InterruptGame(int pid, unsigned long value, unsigned long bufaddr)
{
    *(u32 *)((int)shmaddr + SHM_MSG_BUFFER_ADDRESS) = bufaddr;
    *(u32 *)((int)shmaddr + SHM_CART_INT_REGISTER) = value;
    kill(pid,  SIGCART);
}

void
HandleIoctl(ClientPtr client, IoctlRequest *ioc)
{
    int reply;
    EventFromGame game;
    
    switch (ioc->request) {
    
    case U64_READ: {
	u64_read_arg_t readarg;
	int count, *addr;
	
        if (verbose_flag)
	    fprintf(stderr, "Driverd: U64_READ client %d\n", client->id);	
	readn(client->fd, &readarg, sizeof(readarg));

	/* Now grab data out of shared buffer and send to client */
	addr = (int *)((int)shmaddr + (readarg.ramrom_addr - RAMROM_MSG_ADDR));
	count = *addr++;
	if (count > readarg.nbytes)
	    count = readarg.nbytes;
	write(client->fd, &count, sizeof(count));
	write(client->fd, addr, count);
	/* We have data, ok for game to continue */
	InterruptGame(EmulatorClient->id, readarg.value, 0);
	/* wait for response interrupt */
	readn(EmulatorClient->fd, &game, sizeof(game));
	reply = count;
	Trace("U64_READ done\n");
	break;

    }
    
    case U64_SAFE_WRITE: {
	u64_write_arg_t writearg;
	int count, *addr;
	
        if (verbose_flag)
	    fprintf(stderr, "Driverd: U64_SAFE_WRITE client %d\n", client->id);	
	readn(client->fd, &writearg, sizeof(writearg));

	readn(client->fd, writebuffer, writearg.nbytes);

	/*
	 * First stop the game from accessing the ROM (wait for reply)
	 */
	InterruptGame(EmulatorClient->id, HOST_PIACCESS_REQ, 0);
	/* wait for response interrupt */
	readn(EmulatorClient->fd, &game, sizeof(game));
	Trace("U64_SAFE_WRITE first game intr\n");
	
	/* now transfer the data */
	addr = (int *)((int)shmaddr + (writearg.ramrom_addr - RAMROM_MSG_ADDR));
	*addr++ = writearg.nbytes;
	bcopy(writebuffer, addr, writearg.nbytes);
	InterruptGame(EmulatorClient->id, writearg.value, writearg.ramrom_addr);
	
	/* wait for response interrupt */
	readn(EmulatorClient->fd, &game, sizeof(game));
	Trace("U64_SAFE_WRITE second game intr\n");
	/* Tell client that ioctl is done */
	write(client->fd, &reply, sizeof(reply));
	Trace("U64_SAFE_WRITE done\n");
	break;

    }
    case U64_WRITE: {
	u64_write_arg_t writearg;
	int count, *addr;
	
        if (verbose_flag)
	    fprintf(stderr, "Driverd: U64_WRITE client %d\n", client->id);	
	readn(client->fd, &writearg, sizeof(writearg));

	readn(client->fd, writebuffer, writearg.nbytes);

	/* now transfer the data */
	addr = (int *)((int)shmaddr + (writearg.ramrom_addr - RAMROM_MSG_ADDR));
	*addr++ = writearg.nbytes;
	bcopy(writebuffer, addr, writearg.nbytes);
	InterruptGame(EmulatorClient->id, writearg.value, writearg.ramrom_addr);
	
	/* wait for response interrupt */
	readn(EmulatorClient->fd, &game, sizeof(game));
	/* Tell client that ioctl is done */
	write(client->fd, &reply, sizeof(reply));
	Trace("U64_WRITE done\n");
	break;

    }
    
    case U64_LISTEN: {
	int event, sendevent;
	EventFromGame game;
	
        if (verbose_flag)
	    fprintf(stderr, "Driverd: U64_LISTEN client %d\n", client->id);	
	readn(client->fd, &event, sizeof(event));
	if (eventfdlist[event] == -1)
	    sendevent = 1;
	else
	    sendevent = 0;
	eventfdlist[event] = client->fd;
	if (sendevent) {
	    game.event = event;
	    ProcessEventFromGame(client, &game);
	}
	break;
    }
    
    default:
	fprintf(stderr, "Driverd: HandleIoctl(): unknown ioctl 0x%x\n", ioc->request);
    }
}

/*
 * Read a command or event from the specified file descriptor.
 */
void
readRequestFromClient(ClientPtr client)
{
    int pend;
    int numread;
    unsigned int data[256]; /* XXX enough?  maybe we should malloc? */
    int i;
    unsigned int dd_header;

    if (ioctl(client->fd, FIONREAD, (char *) &pend) < 0) {
	fprintf(stderr, 
	    "Driverd: readRequestFromClient(): Unable to check to see how many bytes are pending.\n");
	/* XXX exit? */
    } else {
	if (pend == 0) {
	    /*
	     * Client's gone.  Nuke 'em, and remove them from the AllSockets
	     * fd_set, so that select won't continuously return, telling us to
	     * read zero bytes of data from a dead client.
	     */
	     CloseDownClient(client);
	     /* XXX return? */
	}
	readn(client->fd, &dd_header, sizeof(dd_header));

#ifdef DEBUG
	fprintf(stderr, "Driverd: fd %d, numread = %d, pend num = %d, dd_header 0x%x\n", 
	client->fd, numread, pend, dd_header);
	fflush(stderr);
#endif
	/*
	 * Determine what kind of command we received, and invoke the 
	 * appropriate action.  
	 *
	 * XXX assumes that we always read complete command buffers; 
	 * we must check to see if we have read a complete command struct here.
	 */
	switch (dd_header) {
	    case DRIVERD_REGISTER_SESSION:
	    {
		RegisterSession session;
		
		numread = readn(client->fd, &session.id,
		    sizeof(RegisterSession) - sizeof(dd_header));
		if (numread != sizeof(RegisterSession) - sizeof(dd_header)) {
		    fprintf(stderr, 
			"Driverd: RS - read mismatch from %d: exp %d bytes, read %d\n",
			client->fd, sizeof(RegisterSession), numread);
		} else {
		    RegisterClient(client, &session);
		}
		break;
	
	    }
	    case DRIVERD_REGISTER_EMULATOR: {
		RegisterEmulator emulator;
		
		numread = readn(client->fd, &emulator.id,
		    sizeof(RegisterEmulator) - sizeof(dd_header));
		if (numread != sizeof(RegisterEmulator) - sizeof(dd_header)) {
		    fprintf(stderr, 
			"Driverd: RE - read mismatch from fd %d: %d != %d\n",
			client->fd, sizeof(RegisterEmulator), numread);
		} else {
		    RegisterEmulatorClient(client, &emulator);
		}
		break;
	    }
	    case DRIVERD_EVENT_FROM_GAME:  {
		EventFromGame game;
		
		numread = readn(client->fd, &game.event, 
		    sizeof(EventFromGame) - sizeof(dd_header));
		if (numread != sizeof(EventFromGame) - sizeof(dd_header)) {
		    fprintf(stderr, 
			"Driverd: EG - read mismatch from fd %d: %d != %d\n",
			client->fd, sizeof(EventFromGame), numread);
		} else {
		    ProcessEventFromGame(client, &game);
		}
		break;
	    }
	    case DRIVERD_IOCTL_REQUEST: {
		IoctlRequest request;
		
		numread = readn(client->fd, &request.request, 
		    sizeof(IoctlRequest) - sizeof(dd_header));
		if (numread != sizeof(IoctlRequest) - sizeof(dd_header)) {
		    fprintf(stderr, 
			"Driverd: IR - read mismatch from fd %d: %d != %d\n",
			client->fd, numread,
			sizeof(IoctlRequest) - sizeof(dd_header));
		} else {
		    HandleIoctl(client, &request);
		}
		break;
	    }
	    default:
		fprintf(stderr, "Driverd: Unexpected action 0x%x from client fd %d\n", 
		    dd_header, client->fd);
		break;
	}
    }
}

void
Dispatch(void)
{
    int	result;
    ClientPtr	client;
    int	nready;
    int i;

    nextFreeClientID = 0;
    nClients = 0;

    while (1)
    {
	nready = WaitForSomething();

	/*
	 * Check for clients with work for us to do.  Process them in fd order
	 * (not necessarily fair, but we'll get to everyone eventually).
	 */
	for (i = 0; i < nClients; i++) {
	    if (FD_ISSET(clients[i]->fd, &SelectReturnMask)) {
		FD_CLR(clients[i]->fd, &SelectReturnMask);
		/*
		 * Read from the socket & do driver emulation stuff.
		 */
		readRequestFromClient(clients[i]);
	    }
	}

	/*
	 * Check for new clients seeking to establish a private fd comm link 
	 * with the daemon.
	 */

	for (i = 0; i < numListeningSockets; i++) {
	    if (FD_ISSET(ListeningSockets[i], &SelectReturnMask)) {

		FD_CLR(ListeningSockets[i], &SelectReturnMask);
		EstablishNewConnection((void *)&ListeningSockets[i]);
	    }
	}
    }
}