dbg_comm.c 30.7 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 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
/*
 * Copyright (c) 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.
 *
 * Module: dbg_comm.c:	host interface routines which allow host programs to 
 *			send commands to the diagnostic monitor agent on the
 *			target system..
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#ifdef __sgi__
#include <sys/sbd.h>
#endif
#include <sys/socket.h>
#include <sys/param.h>
#include <netinet/in.h>
#include <netdb.h>
#ifdef __sgi__
#include <bstring.h>
#endif
#include <dbgproto.h>
#ifdef __sgi__
#include <rkapi.h>
#endif
#include <malloc.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>

#include <sys/mman.h>
#ifdef __sgi__
#include <sys/sema.h>
#include <sys/u64driver.h>
#else
#include <PR/R4300.h>
#endif
#include <sys/u64gio.h>

#include <diag.h>
#include <dbg_comm.h>
#include <tinymon.h>

dbg_comm_struct dbg_comm;

extern int	dgOpenConnection(void);
extern KKHeader	*dgReceiveEvent(void);
extern int	dgSendRequest(void *request);
extern KKHeader	*dgHandleInput(void);
extern int	dgSetComm (int how, unsigned int addr);
extern int	dgInitDbgifComm(void);
extern void	dgReadMemFatalError(unsigned int nbytes, unsigned int addr, 
			int bytesRead);
extern char 	*dgFindFile(char *fullpath, char *postRootSuffix, char *fname);
extern int	dgReadMemViaDbgif(unsigned int addr, unsigned int nbytes, 
			char *buffer);
extern int	dgWriteMemViaDbgif(unsigned int addr, unsigned int nbytes, 
			char *buffer);
extern int	dgReadWordViaTinymon(unsigned int addr, char *buffer);
extern int	dgWriteWordViaTinymon(unsigned int addr, char *buffer);
extern int	dgLoadTinyMon(char *monitorName, int rdramSafe);

static volatile struct u64_board *pBoard;

/*
 * Global variables to be maintained by dgInitComm():
 *
 * dgMemFree:	pointer to first word of memory that's available after the 
 *		monitor (monitor will be loaded at fixed locations selected
 *		by the commtype variable).
 *
 * dgRdramFree:	pointer to first word of rdram that's freely available
 *		(e.g. after the exception vector table, or after the exception
 *		vector table AND monitor).  We can assume that tinymon will be
 *		loaded in rdram immediately following the exception vector
 *		table.  For the standard rmon case, this model breaks down due
 *		to discontiguous rdram usage (e.g. exception vectors, 
 *		multiple program segments, and stack).  My suggestion: don't
 * 		run tests that depend on these variables when running with 
 *		rmon.
 *
 * dgInitialize: When set, indicates that the target system needs to be
 *		initialized.
 *
 * dgIORevision, dgRACRevision, dgRDPRevision, dgRSPRevision:
 *              Loaded with the RCP revision following initilization.
 *
 */
int dgMemFree = 0;
int dgRdramFree = 0;
int dgInitialize = 1;
int dgIORevision = 0;
int dgRACRevision = 0;
int dgRDPRevision = 0;
int dgRSPRevision = 0;

/*
 * The default thread id for the debugger; I'm not certain that we are using
 * it when we do the top level read/write requests, since in practice any value
 * seemed to suffice, but this value matches the thread id's as reported when
 * I've run applications on the simulator.
 */
#define DEFAULT_TVID	4

/*
 * Sets the default communications link for the debugger and returns the
 * current setting.
 */
int dgSetComm (int how, unsigned int addr)
{
    KKSetCommRequest request;
    KKObjectEvent *event;

    request.header.length = sizeof (KKSetCommRequest);
    request.header.code = _KK_REQ_SETCOMM;
    request.header.error = 0;
    request.how = how;
    request.addr = addr;

    if (dgSendRequest( &request ) ) {
	return(KK_NOP);
    }

    /* 
     * wait for reply 
     */
    event = (KKObjectEvent *) dgReceiveEvent ();
    if (event->header.error != 0)
        return (event->header.error);
    else
	return (event->object);
}

/*
 * Uses the ide maintained global variable "commtype", which can be set
 * to one of the values defined in the header file diag.h.
 */
int dgInitComm() 
{
    unsigned int revision;
    int mmemFd;
    unsigned char *mapbase;
    char monitor[80];
    char cmdName[80];
    char shellcmd[256];
    int retval;

    switch (commtype) {
	case DG_VERILOG:
	    if ( dgInitDbgifComm() ) {
	        return(1);
	    } 
	    /*
	     * For DG_VERILOG only, write to a bogus address (0xffff0000)
	     * which will force the verilog model to reset itself.
	     */
	    dgWriteWord(0xffff0000, 0x0);

	    dgMemFree = 0x0;
	    dgRdramFree = 0x0;

	    /* inidicate that the hardware is initialized */
	    dgInitialize = 0;

	    break;
	case DG_RMON:
	    /*
	     * Assume game is loaded already; try to connect to it.
	     */
	    if ( dgInitDbgifComm() ) {
	        return(1);
	    }
	    /*
	     * XXX how do we figure out rdram usage in this situation?
	     */
	    dgMemFree = 0x400;
	    dgRdramFree = 0x400; /* at a minimum, reserve exception vectors */

	    /* inidicate that the hardware is initialized */
	    dgInitialize = 0;

	    break;
	case DG_RMON_RESET:
	    errlog(ERR_SEVERE,
	      "dgInitComm(): no support for DG_RMON_RESET yet!\n");
	    return(1);
	    break;
	case DG_TINYMON_PIF:
	    /*
	     * mmap the development board & set up global pointers so that
	     * the monitor read/write routines can access ramrom & the giobus
	     * registers.
	     */
	    if ((mmemFd = open("/dev/mmem", 2)) < 0) {
		perror("open of /dev/mmem failed");
		return(1);
	    }

	    if ((mapbase = (unsigned char *)mmap(0, U64_GIOBUS_SIZE, 
	      PROT_READ|PROT_WRITE,
	      (MAP_PRIVATE), mmemFd,
	      PHYS_TO_K1(U64_GIOBUS_BASE))) == (unsigned char *)-1) {
		errlog(ERR_SEVERE,
		  "dgInitComm(): cannot map 0x%x.\n", 
		  U64_GIOBUS_BASE);
		perror("mmap");
		return(1);
	    }

	    pBoard = (struct u64_board *)(mapbase);

	    /*
	     * Now load the ramrom based tinymon into the development board,
	     * using the gload program.
	     */
	    if (! dgFindFile(monitor, "/usr/diags/ucode", "tinymon_pif.rom"))
	        errlog(ERR_SEVERE,"Could not find file tinymon_pif.rom");
	    if (monitor == NULL) {
		return(1);
	    }
	    if (! dgFindFile(cmdName, "/usr/sbin", "gload"))
		errlog(ERR_SEVERE,"Could not find file gload");
		
	    if (cmdName == NULL) {
		return(1);
	    } else {
		/*
		 * Get the string arg for "system" ready to go...
		 */
		sprintf(shellcmd, "%s -s %s", cmdName, monitor);
		if ( (retval = system(shellcmd)) != 0) {
		    errlog(ERR_SEVERE, 
		"dgInitComm(): unable to execute %s, shell exit status %d\n",
			shellcmd, retval);
		    return(1);
		} else {
		    /*
		    errlog(INFO, "dgInitComm: gload successful.");
		    */
		}
	    }
	    /*
	     * RDRAM is a free-for-all.
	     */
	    dgMemFree = 0x0;
	    dgRdramFree = 0x0;

	    /* 
	     * Indicate that the hardware is initialized 
	     */
	    dgInitialize = 0;
	    break;

	case DG_TINYMON_RDRAM:
	    dgLoadTinyMon("tm_rdram.rom", 0x800);
	    break;
	case DG_TINYMON_IMEM:
	    dgLoadTinyMon("tm_imem.rom", 0x0);
	    break;
	case DG_TINYMON_DMEM:
	    dgLoadTinyMon("tm_imem.rom", 0x0);
	    break;
	default:
	    errlog(ERR_SEVERE,
	      "dgInitComm(): illegal comm type %d\n", commtype);
	    return(1);
	    break;
    }

    /* Until John fixes the ^C bug, read the revision register twice to
    *  fix the handshake.
    */
    dgReadWord(0x04300004, &revision);
    dgReadWord(0x04300004, &revision);

    switch (revision) {
    case 0x01010101:
	errlog(INFO,"ULTRA64 Development System Ready: RCP v1.0");
	break;

    case 0x02020102:
	errlog(INFO,"ULTRA64 Development System Ready: RCP v2.0");
	break;

    default:
	errlog(INFO, "RCP version 0x%08x not supported.\n", revision);
	errlog(INFO, "Using: RCP v2.0");
	revision = 0x02020102;
	break;
    }

    dgIORevision =  (0xff000000 & revision) >> 24;
    dgRACRevision = (0x00ff0000 & revision) >> 16;
    dgRDPRevision = (0x0000ff00 & revision) >> 8;
    dgRSPRevision = (0x000000ff & revision) >> 0;
    return 0;
}

/*
 * Zero out the comm struct fields, then initialize them as appropriate
 */
int dgInitDbgifComm(void) 
{
    char *meth;

    bzero(&dbg_comm, sizeof(dbg_comm_struct));
    dbg_comm._port = DEFAULT_MASTER_PORT;
    dbg_comm.fildes = -1;	/* This will force a dgOpenConnection */

    /*
     * Do not open the connection immediately.
     * Open it when needed.
     */
    dbg_comm.buf = (char *)malloc(BUFSIZE);
    bzero((char *)dbg_comm.buf, BUFSIZE);
    dbg_comm.bufsize = BUFSIZE;

    /*
     * Return the current settings
     */
    dbg_comm.how = dgSetComm(KK_NOP, 0);

    if ((dbg_comm.how != KK_TCP) && (dbg_comm.how != KK_TTY)) {
        errlog(ERR_SEVERE,
	"dgInitDbgifComm(): connection to dbgif neither TCP/SERIAL??\n");
        return(1);
    }
    if ((meth = getenv("METHOD")) == NULL)
        dbg_comm.method = METHOD_CPU;
    else {
        if (strcmp(meth, "1") == 0)
            dbg_comm.method = METHOD_RCP;
        else
            dbg_comm.method = METHOD_CPU;
    }
    return(0);
}

/*
 * Open and establish a socket connection to the host daemon process dbgif,
 * which will in turn send packets to rmon on the target system.
 */
int dgOpenConnection() {
    int sock;
    char hostname[MAXHOSTNAMELEN + 1];
    struct hostent *hostent;

    /*
     * Create a TCP socket in internet domain using TCP protocol
     */
    if ((sock = socket (AF_INET, SOCK_STREAM, 0)) == -1) {
	perror("socket call failed.");
	return(1);
    }
    if (gethostname (hostname, MAXHOSTNAMELEN) == -1) {
	perror("gethostname call failed.");
	return(1);
    }

    if ((hostent = gethostbyname (hostname)) == NULL) {
	perror("gethostbyname call failed.");
	return(1);
    }

    bzero ((char *)&(dbg_comm.serv_addr), sizeof (struct sockaddr_in));
    bcopy (hostent->h_addr, (char *) &(dbg_comm.serv_addr.sin_addr),
	  hostent->h_length);
    dbg_comm.serv_addr.sin_family = AF_INET;
    dbg_comm.serv_addr.sin_port = dbg_comm._port;

    /* 
     * connect to server
     */
    if (connect(sock, (struct sockaddr *) &(dbg_comm.serv_addr),
		sizeof (struct sockaddr)) == -1) {
	perror("dbgif probably not running, connect call failed");
	return(-1);
    }
    return (sock);
}

int dgSendRequest(void *request)
{
    KKHeader *header = (KKHeader*)request;

    dbg_comm.lastRequest = header->code;	/* save request code */
    header->error = dbg_comm._masterClient;
    header->type = _KK_REQUEST;
    header->rev = TV_DBGPROTO_REV;
    header->method = dbg_comm.method;
    header->notused2 = 0;

    if (dbg_comm.fildes == -1) {
	dbg_comm.fildes = dgOpenConnection();
    }
    if (dbg_comm.fildes == -1) {
	return(1);
    }
    if (write (dbg_comm.fildes, request, header->length) < 0) {
	char errbuf[BUFSIZ];
	sprintf(errbuf, "Send of request '%d' failed", header->code);
	perror(errbuf);
	return(1);
    }
    return(0);
}

/*
 * dgReceiveEvent is usually called after a request is made. It returns
 * the event sent from the target system.
 */
KKHeader *dgReceiveEvent ()
{
    KKHeader *event;
    int result = 0;
    fd_set rmask;

    FD_ZERO(&rmask);
    FD_SET (dbg_comm.fildes, &rmask);

    result = select (dbg_comm.fildes + 1, &rmask, 0, 0, 0);

    if (result == 1) { /* input pending */
	return (dgHandleInput());
    }
    return(0);
}
    
    
/*
 * dgHandleInput is usually called by dgReceiveEvent. It returns the
 * event sent from the target system. It waits for input from the target
 * system, and then reads the event header, determines the size of the event 
 * packet, and then reads the rest of the event.
 */
KKHeader *dgHandleInput ()
{
    KKHeader *event;
    int i, nbytes = 0, size = 0;
    int	success = 0;
    unsigned int bytes_remain, amount;

    do {
	/*
	 * might have to do some peeking here.
	 */
	nbytes = recv (dbg_comm.fildes, dbg_comm.buf, sizeof (KKHeader), 
	    MSG_PEEK);
	if (nbytes == -1 || nbytes == 0) { /* server connection broken */
	    errlog(ERR_SEVERE,
	    "dgHandleInput(): server connection broken.\n");
	    event = (KKHeader *) dbg_comm.buf;
	    event->error = -1;
	    return (event);
	}
	if (nbytes != sizeof (KKHeader))
	    perror ("Unable to read header");
	event = (KKHeader *) dbg_comm.buf;

	/*
	 * If error condition returned, then just pass it back up.
	 */
	if (event->error < 0) {
	    (void) recv (dbg_comm.fildes, dbg_comm.buf, sizeof (KKHeader), 0);
	    return event;
	}

	/*
	 * First time through, buf is NULL and bufsize is zero; realloc
	 * will allocate the storage for us.
	 */
	if (event->length > dbg_comm.bufsize) {
	    dbg_comm.bufsize = (event->length % BUFSIZE) * BUFSIZE + BUFSIZE;
	    dbg_comm.buf = (char *) realloc (dbg_comm.buf, dbg_comm.bufsize);
	}

	/*
	 * read the entire packet, keep peeking at the packet
	 * until all of it appears to be there
	 */
	i = 0;
	bytes_remain = event->length;
	while (bytes_remain) {
	    amount = recv(dbg_comm.fildes, &(dbg_comm.buf[i]), bytes_remain, 0);
	    if (amount < 0)
		perror ("dgHandleInput recv failed: ");
	    bytes_remain -= amount;
	    i += amount;
	}

	/*
	 * Make sure this is the reply we expected, if not decard reply
	 */
	if (event->code != dbg_comm.lastRequest) {
	    printf("Warning: Reply does not match request,"
	    " request = %d, reply = %d\n", dbg_comm.lastRequest, event->code);
	} else {
	    success = 1;
	}

    } while (!success);

    if (event->rev != TV_DBGPROTO_REV)
	printf("version mismatch, expected %d got %d\n",
	       TV_DBGPROTO_REV, event->rev);

    return (event);
}

/*
 * dgReadMem() reads nbytes from the target system address specified by addr,
 * into the caller's data array pointed to by buffer.  The function returns 1
 * if the number of bytes read does not match the number requested; returns 0
 * otherwise.
 */
int dgReadMem(unsigned int addr, unsigned int nbytes, char *buffer)
{
    int wordsRead = 0;

    switch (commtype) {
	case DG_VERILOG:
	    /*
	     * The IoWrite interface to verilog only supports 32 word transfers
	     * maximum.  We break it up into a single word at a time, to match
	     * what we will have with tinymon.
	     */
	    while (wordsRead < nbytes) {
		if ( dgReadMemViaDbgif(addr, sizeof(unsigned int), buffer) ) {
		    return(1);
		}
		addr += sizeof(unsigned int);
		buffer += sizeof(unsigned int);
		wordsRead += sizeof (unsigned int);
	    }
	    break;
	case DG_RMON:
	    break;
	case DG_RMON_RESET:
	    break;
	case DG_TINYMON_PIF:
	case DG_TINYMON_IMEM:
	case DG_TINYMON_DMEM:
	case DG_TINYMON_RDRAM:
	    /*
	     * Protocol is identical for all flavors of tinymon.  We only read
	     * a word at a time.
	     */
	    while (wordsRead < nbytes) {
		if ( dgReadWordViaTinymon(addr, buffer) ) {
		    return(1);
		}
		addr += sizeof(unsigned int);
		buffer += sizeof(unsigned int);
		wordsRead += sizeof (unsigned int);
	    }
	    break;
	default:
	    errlog(ERR_SEVERE,
	      "dgReadMem(): illegal comm type %d\n", commtype);
	    return(1);
	    break;
    }
return(0);
}

/*
 * dgDmaReadMem() uses the tinymon protocol to setup a DMA operation from 
 * rdram to ramrom.
 */
dgDmaReadMem(unsigned int ramromAddr, unsigned int rdramAddr, 
unsigned int nbytes)
{
    int wordsRead = 0;

    switch (commtype) {

	case DG_TINYMON_IMEM:
	case DG_TINYMON_DMEM:
	case DG_TINYMON_RDRAM:
	    if ( dgDmaReadMemViaTinymon(ramromAddr, rdramAddr, nbytes) ) {
		return(1);
	    }
	    break;
	case DG_VERILOG:
	case DG_RMON:
	case DG_RMON_RESET:
	case DG_TINYMON_PIF:
	    errlog(ERR_SEVERE,
	      "dgDmaReadMem(): unsupported comm type %d\n", commtype);
	    return(1);
	default:
	    errlog(ERR_SEVERE,
	      "dgDmaReadMem(): illegal comm type %d\n", commtype);
	    return(1);
	    break;
    }
    return(0);
}

int dgReadMemViaDbgif(unsigned int addr, unsigned int nbytes, char *buffer)
{
    KKReadRequest request;
    KKBufferEvent *event;
    unsigned int size = 0;
    unsigned int req_size = nbytes;
    unsigned int total_size = 0;

    request.header.length = sizeof (KKReadRequest);
    request.header.code = _KK_REQ_READMEM;
    request.object = DEFAULT_TVID;
    if (dbg_comm.how == KK_TCP) {
	/*
	 * Assuming a bandwidth of 1Mb/sec
	 */
	request.addr = addr;
	request.nbytes = nbytes;
	if (dgSendRequest( &request ) ) {
	    return(1);
	}
	/*
	 * wait for reply
	 */
	event = (KKBufferEvent *) dgReceiveEvent ();
	if (event->header.error < 0) {
	    errlog(ERR_SEVERE,
		"dgReadMemViaDbgif(): requested %d bytes from 0x%x, read 0.\n",
		nbytes, addr);
	    return(1);
	}
	size = event->header.length - (sizeof (KKHeader) + sizeof (TVid));
	bcopy (event->buffer, buffer, request.nbytes);
	if (request.nbytes != nbytes) {
	    errlog(ERR_SEVERE,
		"dgReadMemViaDbgif(): requested %d bytes from 0x%x, read %d.\n",
		nbytes, addr, request.nbytes);
	    return(1);
	} else {
	    return(0);
	}
    }

    if (dbg_comm.how == KK_TTY) {
	/*
	 *  9600 baud => 9600 bits/second.  Doubling it as a factor of safety
	 */
	while ((int)req_size > 0) {
	    request.addr = addr + total_size;
	    request.nbytes =
		(req_size >= TV_DBG_MAXREQ_SIZE)?TV_DBG_MAXREQ_SIZE:req_size;
	    dgSendRequest( &request );

	    /*
	     * wait for reply 
	     */
	    event = (KKBufferEvent *) dgReceiveEvent ();
	    if (event->header.error < 0) {
		dgReadMemFatalError(nbytes, addr, 0);
		return(1);
	    }
	    size = event->header.length - (sizeof (KKHeader) + sizeof (TVid));
	    if (size <= 0) {
		dgReadMemFatalError(nbytes, addr, 0);
		return(1);
	    }
	    bcopy (event->buffer, buffer + total_size, request.nbytes);
	    total_size += size;
	    req_size -= size;
	}
	if (nbytes != total_size) {
	    dgReadMemFatalError(nbytes, addr, total_size);
	    return(1);
	} 
	return(0);
    }
    errlog(ERR_SEVERE, 
      "dgReadMemViaDbgif(): bogus comm type %d\n", dbg_comm.how);
    return(1);
}

/*
 * Use the tinymon protocol to read a word of data from the R4300's address
 * space.
 */
int dgReadWordViaTinymon(unsigned int addr, char *buffer)
{
    unsigned int *ramromBase;
    unsigned int regValue;
    if (addr == 0x80000000) {
	/* printf("interrupt = %x\n", *( ((unsigned int *)pBoard) + 0x00000)); */
	printf("RDB read = 0x%x\n", *( ((unsigned int *)pBoard) + 0x20000));
	*( ((unsigned int *)pBoard) + 0x20000) = 0x12345678;
	return(0);
    }

    pBoard->cart_interrupt = DG_RAMROM_REQUEST;
    regValue = pBoard->gio_sync;
    while ( (regValue & _U64_REGMASK) != DG_RAMROM_GRANT ) {
	regValue = pBoard->gio_sync;
    }
    /*
     * Write the read command into the first two words of ramrom.
     * First word = command type (DG_TINYMON_READ_OP)
     * Second word = address to read.
     *
     * Set the dram page control to zero; don't bother shifting zero into
     * position within the 32 bit word, as a zero write will zap those bits.
     */
    pBoard->dram_page_cntrl = 0; /* gets us onto the first page of ramrom */
    ramromBase = ((unsigned int *) ( ((unsigned int)pBoard) + U64_MEM_SIZE) );

    *ramromBase++ = DG_TINYMON_READ_OP;
    if (commtype == DG_TINYMON_PIF)
	*ramromBase++ = addr;
    else
	*ramromBase++ = PHYS_TO_K1(addr);
    /*
     * Tell the R4300 to execute our command request, and wait for its response.
     */
    pBoard->cart_interrupt = DG_RAMROM_CMD_READY;
    regValue = pBoard->gio_sync;
    while ( (regValue & _U64_REGMASK) != DG_RAMROM_CMD_DONE ) {
	regValue = pBoard->gio_sync;
    }

    /*
     * The third word of ramrom has our data.
     */

    *( (unsigned int *)buffer ) = *ramromBase;
    return(0);
}

/*
 * Use the tinymon protocol to setup a DMA operation from rdram to ramrom.
 */
int	
dgDmaReadMemViaTinymon(unsigned int ramromAddr, unsigned int rdramAddr, 
unsigned int nbytes)
{
    unsigned int *ramromBase;
    unsigned int regValue;

    /*
     * Tell the R4300 we want to yank their chain, and wait for its response.
     */
    pBoard->cart_interrupt = DG_RAMROM_REQUEST;
    regValue = pBoard->gio_sync;
    while ( (regValue & _U64_REGMASK) != DG_RAMROM_GRANT ) {
	regValue = pBoard->gio_sync;
    }
    /*
     * Write the dma read command into the first four words of ramrom.
     * First word = command type (DG_TINYMON_DMA_READ_OP)
     * Second word = ramrom address to write to
     * Third word = rdram address to read from
     * Fourth word = number of bytes to transfer.
     *
     * Set the dram page control to zero; don't bother shifting zero into
     * position within the 32 bit word, as a zero write will zap those bits.
     */
    pBoard->dram_page_cntrl = 0; /* gets us onto the first page of ramrom */
    ramromBase = ((unsigned int *) ( ((unsigned int)pBoard) + U64_MEM_SIZE) );

    *ramromBase++ = DG_TINYMON_DMA_READ_OP;
    *ramromBase++ = ramromAddr; /* Use physical addresses, not K1 seg addrs */
    *ramromBase++ = rdramAddr;
    *ramromBase++ = nbytes;

    /*
     * Tell the R4300 to execute our command request, and wait for its response.
     */
    pBoard->cart_interrupt = DG_RAMROM_CMD_READY;
    regValue = pBoard->gio_sync;
    while ( (regValue & _U64_REGMASK) != DG_RAMROM_CMD_DONE ) {
	regValue = pBoard->gio_sync;
    }
    return(0);
}

/*
 * dgDmaWriteMem() uses the tinymon protocol to setup a DMA operation from 
 * ramrom to rdram.
 */
dgDmaWriteMem(unsigned int ramromAddr, unsigned int rdramAddr, 
unsigned int nbytes)
{
    int wordsRead = 0;

    switch (commtype) {

	case DG_TINYMON_IMEM:
	case DG_TINYMON_DMEM:
	case DG_TINYMON_RDRAM:
	    if ( dgDmaWriteMemViaTinymon(ramromAddr, rdramAddr, nbytes) ) {
		return(1);
	    }
	    break;
	case DG_VERILOG:
	case DG_RMON:
	case DG_RMON_RESET:
	case DG_TINYMON_PIF:
	    errlog(ERR_SEVERE,
	      "dgDmaWriteMem(): unsupported comm type %d\n", commtype);
	    return(1);
	default:
	    errlog(ERR_SEVERE,
	      "dgDmaWriteMem(): illegal comm type %d\n", commtype);
	    return(1);
	    break;
    }
    return(0);
}

/*
 * Use the tinymon protocol to setup a DMA operation from ramrom to rdram.
 */
int	
dgDmaWriteMemViaTinymon(unsigned int ramromAddr, unsigned int rdramAddr, 
unsigned int nbytes)
{
    unsigned int *ramromBase;
    unsigned int regValue;

    /*
     * Tell the R4300 we want to yank their chain, and wait for its response.
     */
    pBoard->cart_interrupt = DG_RAMROM_REQUEST;
    regValue = pBoard->gio_sync;
    while ( (regValue & _U64_REGMASK) != DG_RAMROM_GRANT ) {
	regValue = pBoard->gio_sync;
    }
    /*
     * Write the dma read command into the first four words of ramrom.
     * First word = command type (DG_TINYMON_DMA_WRITE_OP)
     * Second word = ramrom address to write to
     * Third word = rdram address to read from
     * Fourth word = number of bytes to transfer.
     *
     * Set the dram page control to zero; don't bother shifting zero into
     * position within the 32 bit word, as a zero write will zap those bits.
     */
    pBoard->dram_page_cntrl = 0; /* gets us onto the first page of ramrom */
    ramromBase = ((unsigned int *) ( ((unsigned int)pBoard) + U64_MEM_SIZE) );

    *ramromBase++ = DG_TINYMON_DMA_WRITE_OP;
    *ramromBase++ = ramromAddr; /* Use physical addresses, not K1 seg addrs */
    *ramromBase++ = rdramAddr;
    *ramromBase++ = nbytes;

    /*
     * Tell the R4300 to execute our command request, and wait for its response.
     */
    pBoard->cart_interrupt = DG_RAMROM_CMD_READY;
    regValue = pBoard->gio_sync;
    while ( (regValue & _U64_REGMASK) != DG_RAMROM_CMD_DONE ) {
	regValue = pBoard->gio_sync;
    }
    return(0);
}

/*
 * dgWriteMem attempts to write nbytes to the target system address specified
 * by addr, from the buffer pointed to by buffer.
 */
int dgWriteMem(unsigned int addr, unsigned int nbytes, char *buffer)
{
    int wordsWritten = 0;

    switch (commtype) {
	case DG_VERILOG:
	    /*
	     * The IoWrite interface to verilog only supports 32 word transfers
	     * maximum.  We break it up into a single word at a time, to match
	     * what we will have with tinymon.
	     */
	    while (wordsWritten < nbytes) {
		if ( dgWriteMemViaDbgif(addr, sizeof(unsigned int), buffer) ) {
		    return(1);
		}
		addr += sizeof(unsigned int);
		buffer += sizeof(unsigned int);
		wordsWritten += sizeof (unsigned int);
	    }
	    break;
	case DG_RMON:
	    break;
	case DG_RMON_RESET:
	    break;
	case DG_TINYMON_PIF:
	case DG_TINYMON_IMEM:
	case DG_TINYMON_DMEM:
	case DG_TINYMON_RDRAM:
	    /*
	     * Protocol is identical for all flavors of tinymon.  We only write
	     * a word at a time.
	     */
	    while (wordsWritten < nbytes) {
		if ( dgWriteWordViaTinymon(addr, buffer) ) {
		    return(1);
		}
		addr += sizeof(unsigned int);
		buffer += sizeof(unsigned int);
		wordsWritten += sizeof (unsigned int);
	    }
	    break;
	default:
	    errlog(ERR_SEVERE,
	      "dgWriteMem(): illegal comm type %d\n", commtype);
	    return(1);
	    break;
    }
    return(0);
}

int dgWriteMemViaDbgif(unsigned int addr, unsigned int nbytes, 
	char *buffer)
{
    KKWriteRequest *request;
    KKObjectEvent *event;
    unsigned int req_size = nbytes;
    unsigned int total_size = 0;
    char *allocated_buffer;
    
    allocated_buffer = (char *) 
	malloc(sizeof(KKWriteHeader) + TV_DBG_MAXREQ_SIZE);
    request = (KKWriteRequest *)allocated_buffer;

    request->writeHeader.header.length = sizeof (KKWriteRequest);
    request->writeHeader.header.code = _KK_REQ_WRITEMEM;
    request->writeHeader.object = DEFAULT_TVID;

    while ((int)req_size > 0) {
	request->writeHeader.addr = addr + total_size;
	request->writeHeader.nbytes =
	    (req_size >= TV_DBG_MAXREQ_SIZE) ? TV_DBG_MAXREQ_SIZE : req_size;
	bcopy (buffer + total_size, request->buffer,
		request->writeHeader.nbytes);

	if (dgSendRequest( request ) ) {
	    return(1);
	}

	/*
	 * wait for reply 
	 */
	event = (KKObjectEvent *)dgReceiveEvent ();
	if (event->header.error < 0) {
	    free(allocated_buffer);
	    errlog(ERR_SEVERE,
	    "dgWriteMemViaDbgif(): reply from monitor had error %d\n", 
	    event->header.error);
	    return(1);
	}
	req_size -= request->writeHeader.nbytes;
	total_size += request->writeHeader.nbytes;
    }

    free(allocated_buffer);

    if (nbytes != total_size) {
	errlog(ERR_SEVERE,
	  "dgWriteMemViaDbgif(): requested %d bytes for 0x%x, wrote %d.\n",
	  nbytes, addr, total_size);
	return(1);
    }
    return(0);
}

/*
 * Use the tinymon protocol to write a word into the R4300's address space.
 * XXX put timeouts into the spin loops?
 */
int dgWriteWordViaTinymon(unsigned int addr, char *buffer)
{
    unsigned int *ramromBase;
    unsigned int regValue;

    /*
     * Tell the R4300 we want to yank their chain, and wait for its response.
     */
    pBoard->cart_interrupt = DG_RAMROM_REQUEST;
    regValue = pBoard->gio_sync;
    while ( (regValue & _U64_REGMASK) != DG_RAMROM_GRANT ) {
	regValue = pBoard->gio_sync;
    }
    /*
     * Put the write command into the first three words of ramrom.
     *
     * First word  = command type (DG_TINYMON_WRITE_OP)
     * Second word = address to write to.
     * Third word  = data to be written to above address.
     *
     * Set the dram page control to zero; don't bother shifting zero into
     * position within the 32 bit word, as a zero write will zap those bits.
     */
    pBoard->dram_page_cntrl = 0; /* gets us onto the first page of ramrom */
    ramromBase = ((unsigned int *) ( ((unsigned int)pBoard) + U64_MEM_SIZE) );

    *ramromBase++ = DG_TINYMON_WRITE_OP;
    if (commtype == DG_TINYMON_PIF)
	*ramromBase++ = addr;
    else
	*ramromBase++ = PHYS_TO_K1(addr);
    *ramromBase++ = *( (unsigned int *)buffer );
    /*
     * Tell the R4300 to execute our command request, and wait for its response.
     */
    pBoard->cart_interrupt = DG_RAMROM_CMD_READY;
    regValue = pBoard->gio_sync;
    while ( (regValue & _U64_REGMASK) != DG_RAMROM_CMD_DONE ) {
	regValue = pBoard->gio_sync;
    }
    return(0);
}

void dgReadMemFatalError(unsigned int nbytes, unsigned int addr, int bytesRead)
{
    errlog(ERR_SEVERE,
	"dgReadMem(): requested %d bytes from 0x%x, read %d.\n",
	nbytes, addr, bytesRead);
}

/*
 * Convenience wrapper
 */
int dgReadWord(unsigned int addr, unsigned int *word)
{
    if (addr == 0x80000000) {
        /* printf("interrupt = %x\n", *( ((unsigned int *)pBoard) + 0x00000)); */
        printf("RDB read = 0x%x\n", *( ((unsigned int *)pBoard) + 0x20000));
        *( ((unsigned int *)pBoard) + 0x20000) = 0x12345678;
        return(0);
    }

    return(dgReadMem(addr, 4, ((char *)word)));
}

/*
 * Convenience wrapper
 */
int dgWriteWord(unsigned int addr, unsigned int word)
{
    return(dgWriteMem(addr, 4, ((char *)&word)));
}

char *
dgFindFile(char *fullpath, char *postRootSuffix, char *fname)
{
    char *rootname, *rootpath;
    int fd;
    int try;

    for (try = 0; try <= 2; try++) {
	fullpath[0] = '\0';

	switch (try) {
	    case 0: rootname = "ROOT"; break;
	    case 1: rootname = "WORKAREA"; break;
	    case 2: rootname = NULL; break;
	}

	if (rootname != NULL) {
	    if ((rootpath = (char *)getenv(rootname)) == NULL)
		continue;
	    strcat(fullpath, rootpath);
	}

	if (postRootSuffix) {
	    strcat(fullpath, postRootSuffix);
	    strcat(fullpath, "/");
	}

	strcat(fullpath, fname);

	if (!access(fullpath, R_OK)) 
	    return(fullpath);
	    
    }

    *fullpath = '\0';
    return(NULL);
}

dgLoadTinyMon(char *monitorName, int rdramSafe)
{
    int mmemFd;
    unsigned char *mapbase;
    char monitor[80];
    char cmdName[80];
    char shellcmd[256];
    int retval;

    /*
     * mmap the development board & set up global pointers so that
     * the monitor read/write routines can access ramrom & the giobus
     * registers.
     */
    if ((mmemFd = open("/dev/mmem", 2)) < 0) {
	perror("open of /dev/mmem failed");
	return(1);
    }

    if ((mapbase = (unsigned char *)mmap(0, U64_GIOBUS_SIZE, 
      PROT_READ|PROT_WRITE,
      (MAP_PRIVATE), mmemFd,
      PHYS_TO_K1(U64_GIOBUS_BASE))) == (unsigned char *)-1) {
	errlog(ERR_SEVERE,
	  "dgInitComm(): cannot map 0x%x.\n", 
	  U64_GIOBUS_BASE);
	perror("mmap");
	return(1);
    }

    pBoard = (struct u64_board *)(mapbase);

    /*
     * Load the rdram based tinymon into the development board using the 
     * gload program.
     */
    if (! dgFindFile(monitor, "/usr/diags/ucode", monitorName))
	errlog(ERR_SEVERE,"Could not find file %s",monitorName);
    if (monitor == NULL) {
	return(1);
    }
    if (! dgFindFile(cmdName, "/usr/sbin", "gload"))
	errlog(ERR_SEVERE,"Could not find file gload");
    if (cmdName == NULL) {
	return(1);
    } else {
	/*
	 * Use the "system" syscall to fire off gload -s.
	 */
	sprintf(shellcmd, "%s -s %s", cmdName, monitor);
	if ( (retval = system(shellcmd)) != 0) {
	    errlog(ERR_SEVERE, 
	"dgLoadTinyMon(): unable to execute %s, shell exit status %d\n",
		shellcmd, retval);
	    return(1);
	} 
    }
    /*
     * Tell the diag user where they can begin writing to rdram with impunity.
     */
    dgMemFree = rdramSafe;
    dgRdramFree = rdramSafe;

    /* 
     * Indicate that the hardware is initialized 
     */
    dgInitialize = 0;
}