VirtualBox

source: vbox/trunk/src/VBox/GuestHost/OpenGL/util/net.c@ 30045

Last change on this file since 30045 was 21523, checked in by vboxsync, 15 years ago

crOpenGL: add protocol version check(4108), add max connected clients check

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 35.3 KB
Line 
1/* Copyright (c) 2001, Stanford University
2 * All rights reserved
3 *
4 * See the file LICENSE.txt for information on redistributing this software.
5 */
6
7#include <stdio.h>
8#include <stdlib.h>
9#include <stdarg.h>
10#include <errno.h>
11#include <memory.h>
12#include <signal.h>
13
14#ifdef WINDOWS
15#define WIN32_LEAN_AND_MEAN
16#include <process.h>
17#else
18#include <unistd.h>
19#endif
20
21#include "cr_mem.h"
22#include "cr_error.h"
23#include "cr_string.h"
24#include "cr_url.h"
25#include "cr_net.h"
26#include "cr_netserver.h"
27#include "cr_pixeldata.h"
28#include "cr_environment.h"
29#include "cr_endian.h"
30#include "cr_bufpool.h"
31#include "cr_threads.h"
32#include "net_internals.h"
33
34
35#define CR_MINIMUM_MTU 1024
36
37#define CR_INITIAL_RECV_CREDITS ( 1 << 21 ) /* 2MB */
38
39/* Allow up to four processes per node. . . */
40#define CR_QUADRICS_LOWEST_RANK 0
41#define CR_QUADRICS_HIGHEST_RANK 3
42
43static struct {
44 int initialized; /* flag */
45 CRNetReceiveFuncList *recv_list; /* what to do with arriving packets */
46 CRNetCloseFuncList *close_list; /* what to do when a client goes down */
47
48 /* Number of connections using each type of interface: */
49 int use_tcpip;
50 int use_ib;
51 int use_file;
52 int use_udp;
53 int use_gm;
54 int use_sdp;
55 int use_teac;
56 int use_tcscomm;
57 int use_hgcm;
58
59 int num_clients; /* total number of clients (unused?) */
60
61#ifdef CHROMIUM_THREADSAFE
62 CRmutex mutex;
63#endif
64 int my_rank; /* Teac/TSComm only */
65} cr_net;
66
67
68
69/**
70 * Helper routine used by both crNetConnectToServer() and crNetAcceptClient().
71 * Call the protocol-specific Init() and Connection() functions.
72 *
73 */
74static void
75InitConnection(CRConnection *conn, const char *protocol, unsigned int mtu)
76{
77 if (!crStrcmp(protocol, "devnull"))
78 {
79 crDevnullInit(cr_net.recv_list, cr_net.close_list, mtu);
80 crDevnullConnection(conn);
81 }
82 else if (!crStrcmp(protocol, "file"))
83 {
84 cr_net.use_file++;
85 crFileInit(cr_net.recv_list, cr_net.close_list, mtu);
86 crFileConnection(conn);
87 }
88 else if (!crStrcmp(protocol, "swapfile"))
89 {
90 /* file with byte-swapping */
91 cr_net.use_file++;
92 crFileInit(cr_net.recv_list, cr_net.close_list, mtu);
93 crFileConnection(conn);
94 conn->swap = 1;
95 }
96 else if (!crStrcmp(protocol, "tcpip"))
97 {
98 cr_net.use_tcpip++;
99 crTCPIPInit(cr_net.recv_list, cr_net.close_list, mtu);
100 crTCPIPConnection(conn);
101 }
102 else if (!crStrcmp(protocol, "udptcpip"))
103 {
104 cr_net.use_udp++;
105 crUDPTCPIPInit(cr_net.recv_list, cr_net.close_list, mtu);
106 crUDPTCPIPConnection(conn);
107 }
108#ifdef VBOX_WITH_HGCM
109 else if (!crStrcmp(protocol, "vboxhgcm"))
110 {
111 cr_net.use_hgcm++;
112 crVBoxHGCMInit(cr_net.recv_list, cr_net.close_list, mtu);
113 crVBoxHGCMConnection(conn);
114 }
115#endif
116#ifdef GM_SUPPORT
117 else if (!crStrcmp(protocol, "gm"))
118 {
119 cr_net.use_gm++;
120 crGmInit(cr_net.recv_list, cr_net.close_list, mtu);
121 crGmConnection(conn);
122 }
123#endif
124#ifdef TEAC_SUPPORT
125 else if (!crStrcmp(protocol, "quadrics"))
126 {
127 cr_net.use_teac++;
128 crTeacInit(cr_net.recv_list, cr_net.close_list, mtu);
129 crTeacConnection(conn);
130 }
131#endif
132#ifdef TCSCOMM_SUPPORT
133 else if (!crStrcmp(protocol, "quadrics-tcscomm"))
134 {
135 cr_net.use_tcscomm++;
136 crTcscommInit(cr_net.recv_list, cr_net.close_list, mtu);
137 crTcscommConnection(conn);
138 }
139#endif
140#ifdef SDP_SUPPORT
141 else if (!crStrcmp(protocol, "sdp"))
142 {
143 cr_net.use_sdp++;
144 crSDPInit(cr_net.recv_list, cr_net.close_list, mtu);
145 crSDPConnection(conn);
146 }
147#endif
148#ifdef IB_SUPPORT
149 else if (!crStrcmp(protocol, "ib"))
150 {
151 cr_net.use_ib++;
152 crDebug("Calling crIBInit()");
153 crIBInit(cr_net.recv_list, cr_net.close_list, mtu);
154 crIBConnection(conn);
155 crDebug("Done Calling crIBInit()");
156 }
157#endif
158#ifdef HP_MULTICAST_SUPPORT
159 else if (!crStrcmp(protocol, "hpmc"))
160 {
161 cr_net.use_hpmc++;
162 crHPMCInit(cr_net.recv_list, cr_net.close_list, mtu);
163 crHPMCConnection(conn);
164 }
165#endif
166 else
167 {
168 crError("Unknown protocol: \"%s\"", protocol);
169 }
170}
171
172
173
174/**
175 * Establish a connection with a server.
176 * \param server the server to connect to, in the form
177 * "protocol://servername:port" where the port specifier
178 * is optional and if the protocol is missing it is assumed
179 * to be "tcpip".
180 * \param default_port the port to connect to, if port not specified in the
181 * server URL string.
182 * \param mtu desired maximum transmission unit size (in bytes)
183 * \param broker either 1 or 0 to indicate if connection is brokered through
184 * the mothership
185 */
186CRConnection *
187crNetConnectToServer( const char *server, unsigned short default_port,
188 int mtu, int broker )
189{
190 char hostname[4096], protocol[4096];
191 unsigned short port;
192 CRConnection *conn;
193
194 crDebug( "In crNetConnectToServer( \"%s\", port=%d, mtu=%d, broker=%d )",
195 server, default_port, mtu, broker );
196
197 CRASSERT( cr_net.initialized );
198
199 if (mtu < CR_MINIMUM_MTU)
200 {
201 crError( "You tried to connect to server \"%s\" with an mtu of %d, "
202 "but the minimum MTU is %d", server, mtu, CR_MINIMUM_MTU );
203 }
204
205 /* Tear the URL apart into relevant portions. */
206 if ( !crParseURL( server, protocol, hostname, &port, default_port ) ) {
207 crError( "Malformed URL: \"%s\"", server );
208 }
209
210 /* If the host name is "localhost" replace it with the _real_ name
211 * of the localhost. If we don't do this, there seems to be
212 * confusion in the mothership as to whether or not "localhost" and
213 * "foo.bar.com" are the same machine.
214 */
215 if (crStrcmp(hostname, "localhost") == 0) {
216 int rv = crGetHostname(hostname, 4096);
217 CRASSERT(rv == 0);
218 (void) rv;
219 }
220
221 /* XXX why is this here??? I think it could be moved into the
222 * crTeacConnection() function with no problem. I.e. change the
223 * connection's port, teac_rank and tcscomm_rank there. (BrianP)
224 */
225 if ( !crStrcmp( protocol, "quadrics" ) ||
226 !crStrcmp( protocol, "quadrics-tcscomm" ) ) {
227 /* For Quadrics protocols, treat "port" as "rank" */
228 if ( port > CR_QUADRICS_HIGHEST_RANK ) {
229 crWarning( "Invalid crserver rank, %d, defaulting to %d\n",
230 port, CR_QUADRICS_LOWEST_RANK );
231 port = CR_QUADRICS_LOWEST_RANK;
232 }
233 }
234 crDebug( "Connecting to %s on port %d, with protocol %s",
235 hostname, port, protocol );
236
237#ifdef SDP_SUPPORT
238 /* This makes me ill, but we need to "fix" the hostname for sdp. MCH */
239 if (!crStrcmp(protocol, "sdp")) {
240 char* temp;
241 temp = strtok(hostname, ".");
242 crStrcat(temp, crGetSDPHostnameSuffix());
243 crStrcpy(hostname, temp);
244 crDebug("SDP rename hostname: %s", hostname);
245 }
246#endif
247
248 conn = (CRConnection *) crCalloc( sizeof(*conn) );
249 if (!conn)
250 return NULL;
251
252 /* init the non-zero fields */
253 conn->type = CR_NO_CONNECTION; /* we don't know yet */
254 conn->recv_credits = CR_INITIAL_RECV_CREDITS;
255 conn->hostname = crStrdup( hostname );
256 conn->port = port;
257 conn->mtu = mtu;
258 conn->buffer_size = mtu;
259 conn->broker = broker;
260 conn->endianness = crDetermineEndianness();
261 /* XXX why are these here??? Move them into the crTeacConnection()
262 * and crTcscommConnection() functions.
263 */
264 conn->teac_id = -1;
265 conn->teac_rank = port;
266 conn->tcscomm_id = -1;
267 conn->tcscomm_rank = port;
268
269 crInitMessageList(&conn->messageList);
270
271 /* now, just dispatch to the appropriate protocol's initialization functions. */
272 InitConnection(conn, protocol, mtu);
273
274 if (!crNetConnect( conn ))
275 {
276 crDebug("crNetConnectToServer() failed, freeing the connection");
277 #ifdef CHROMIUM_THREADSAFE
278 crFreeMutex( &conn->messageList.lock );
279 #endif
280 conn->Disconnect(conn);
281 crFree( conn );
282 return NULL;
283 }
284
285 crDebug( "Done connecting to %s (swapping=%d)", server, conn->swap );
286 return conn;
287}
288
289
290/**
291 * Send a message to the receiver that another connection is needed.
292 * We send a CR_MESSAGE_NEWCLIENT packet, then call crNetServerConnect.
293 */
294void crNetNewClient( CRConnection *conn, CRNetServer *ns )
295{
296 /*
297 unsigned int len = sizeof(CRMessageNewClient);
298 CRMessageNewClient msg;
299
300 CRASSERT( conn );
301
302 if (conn->swap)
303 msg.header.type = (CRMessageType) SWAP32(CR_MESSAGE_NEWCLIENT);
304 else
305 msg.header.type = CR_MESSAGE_NEWCLIENT;
306
307 crNetSend( conn, NULL, &msg, len );
308 */
309
310 crNetServerConnect( ns );
311}
312
313
314/**
315 * Accept a connection from a client.
316 * \param protocol the protocol to use (such as "tcpip" or "gm")
317 * \param hostname optional hostname of the expected client (may be NULL)
318 * \param port number of the port to accept on
319 * \param mtu maximum transmission unit
320 * \param broker either 1 or 0 to indicate if connection is brokered through
321 * the mothership
322 * \return new CRConnection object, or NULL
323 */
324CRConnection *
325crNetAcceptClient( const char *protocol, const char *hostname,
326 unsigned short port, unsigned int mtu, int broker )
327{
328 CRConnection *conn;
329
330 CRASSERT( cr_net.initialized );
331
332 conn = (CRConnection *) crCalloc( sizeof( *conn ) );
333 if (!conn)
334 return NULL;
335
336 /* init the non-zero fields */
337 conn->type = CR_NO_CONNECTION; /* we don't know yet */
338 conn->recv_credits = CR_INITIAL_RECV_CREDITS;
339 conn->port = port;
340 conn->mtu = mtu;
341 conn->buffer_size = mtu;
342 conn->broker = broker;
343 conn->endianness = crDetermineEndianness();
344 conn->teac_id = -1;
345 conn->teac_rank = -1;
346 conn->tcscomm_id = -1;
347 conn->tcscomm_rank = -1;
348
349 crInitMessageList(&conn->messageList);
350
351 /* now, just dispatch to the appropriate protocol's initialization functions. */
352 crDebug("In crNetAcceptClient( protocol=\"%s\" port=%d mtu=%d )",
353 protocol, (int) port, (int) mtu);
354
355 /* special case */
356 if ( !crStrncmp( protocol, "file", crStrlen( "file" ) ) ||
357 !crStrncmp( protocol, "swapfile", crStrlen( "swapfile" ) ) )
358 {
359 char filename[4096];
360 char protocol_only[4096];
361
362 cr_net.use_file++;
363 if (!crParseURL(protocol, protocol_only, filename, NULL, 0))
364 {
365 crError( "Malformed URL: \"%s\"", protocol );
366 }
367 conn->hostname = crStrdup( filename );
368
369 /* call the protocol-specific init routines */ // ktd (add)
370 InitConnection(conn, protocol_only, mtu); // ktd (add)
371 }
372 else {
373 /* call the protocol-specific init routines */
374 InitConnection(conn, protocol, mtu);
375 }
376
377 crNetAccept( conn, hostname, port );
378 return conn;
379}
380
381
382/**
383 * Close and free given connection.
384 */
385void
386crNetFreeConnection(CRConnection *conn)
387{
388 conn->Disconnect(conn);
389 crFree( conn->hostname );
390 #ifdef CHROMIUM_THREADSAFE
391 crFreeMutex( &conn->messageList.lock );
392 #endif
393 crFree(conn);
394}
395
396
397extern void __getHostInfo();
398/**
399 * Start the ball rolling. give functions to handle incoming traffic
400 * (usually placing blocks on a queue), and a handler for dropped
401 * connections.
402 */
403void crNetInit( CRNetReceiveFunc recvFunc, CRNetCloseFunc closeFunc )
404{
405 CRNetReceiveFuncList *rfl;
406 CRNetCloseFuncList *cfl;
407
408 if ( cr_net.initialized )
409 {
410 /*crDebug( "Networking already initialized!" );*/
411 }
412 else
413 {
414#ifdef WINDOWS
415 WORD wVersionRequested = MAKEWORD(2, 0);
416 WSADATA wsaData;
417 int err;
418
419 err = WSAStartup(wVersionRequested, &wsaData);
420 if (err != 0)
421 crError("Couldn't initialize sockets on WINDOWS");
422 //reinit hostname for debug messages as it's incorrect before WSAStartup gets called
423 __getHostInfo();
424#endif
425
426 cr_net.use_gm = 0;
427 cr_net.use_udp = 0;
428 cr_net.use_tcpip = 0;
429 cr_net.use_sdp = 0;
430 cr_net.use_tcscomm = 0;
431 cr_net.use_teac = 0;
432 cr_net.use_file = 0;
433 cr_net.use_hgcm = 0;
434 cr_net.num_clients = 0;
435#ifdef CHROMIUM_THREADSAFE
436 crInitMutex(&cr_net.mutex);
437#endif
438
439 cr_net.initialized = 1;
440 cr_net.recv_list = NULL;
441 cr_net.close_list = NULL;
442 }
443
444 if (recvFunc != NULL)
445 {
446 /* check if function is already in the list */
447 for (rfl = cr_net.recv_list ; rfl ; rfl = rfl->next )
448 {
449 if (rfl->recv == recvFunc)
450 {
451 /* we've already seen this function -- do nothing */
452 break;
453 }
454 }
455 /* not in list, so insert at the head */
456 if (!rfl)
457 {
458 rfl = (CRNetReceiveFuncList *) crAlloc( sizeof (*rfl ));
459 rfl->recv = recvFunc;
460 rfl->next = cr_net.recv_list;
461 cr_net.recv_list = rfl;
462 }
463 }
464
465 if (closeFunc != NULL)
466 {
467 /* check if function is already in the list */
468 for (cfl = cr_net.close_list ; cfl ; cfl = cfl->next )
469 {
470 if (cfl->close == closeFunc)
471 {
472 /* we've already seen this function -- do nothing */
473 break;
474 }
475 }
476 /* not in list, so insert at the head */
477 if (!cfl)
478 {
479 cfl = (CRNetCloseFuncList *) crAlloc( sizeof (*cfl ));
480 cfl->close = closeFunc;
481 cfl->next = cr_net.close_list;
482 cr_net.close_list = cfl;
483 }
484 }
485}
486
487/* Free up stuff */
488void crNetTearDown()
489{
490 CRNetReceiveFuncList *rfl;
491 CRNetCloseFuncList *cfl;
492 void *tmp;
493
494 if (!cr_net.initialized) return;
495
496#ifdef CHROMIUM_THREADSAFE
497 crLockMutex(&cr_net.mutex);
498#endif
499
500 /* Note, other protocols used by chromium should free up stuff too,
501 * but VBox doesn't use them, so no other checks.
502 */
503 if (cr_net.use_hgcm)
504 crVBoxHGCMTearDown();
505
506 for (rfl = cr_net.recv_list ; rfl ; rfl = (CRNetReceiveFuncList *) tmp )
507 {
508 tmp = rfl->next;
509 crFree(rfl);
510 }
511
512 for (cfl = cr_net.close_list ; cfl ; cfl = (CRNetCloseFuncList *) tmp )
513 {
514 tmp = cfl->next;
515 crFree(cfl);
516 }
517
518 cr_net.initialized = 0;
519
520#ifdef CHROMIUM_THREADSAFE
521 crUnlockMutex(&cr_net.mutex);
522 crFreeMutex(&cr_net.mutex);
523#endif
524}
525
526CRConnection** crNetDump( int* num )
527{
528 CRConnection **c;
529
530 c = crTCPIPDump( num );
531 if ( c ) return c;
532
533 c = crDevnullDump( num );
534 if ( c ) return c;
535
536 c = crFileDump( num );
537 if ( c ) return c;
538
539#ifdef VBOX_WITH_HGCM
540 c = crVBoxHGCMDump( num );
541 if ( c ) return c;
542#endif
543#ifdef GM_SUPPORT
544 c = crGmDump( num );
545 if ( c ) return c;
546#endif
547#ifdef IB_SUPPORT
548 c = crIBDump( num );
549 if ( c ) return c;
550#endif
551#ifdef SDP_SUPPORT
552 c = crSDPDump( num );
553 if ( c ) return c;
554#endif
555
556 *num = 0;
557 return NULL;
558}
559
560
561/*
562 * Allocate a network data buffer. The size will be the mtu size specified
563 * earlier to crNetConnectToServer() or crNetAcceptClient().
564 *
565 * Buffers that will eventually be transmitted on a connection
566 * *must* be allocated using this interface. This way, we can
567 * automatically pin memory and tag blocks, and we can also use
568 * our own buffer pool management.
569 */
570void *crNetAlloc( CRConnection *conn )
571{
572 CRASSERT( conn );
573 return conn->Alloc( conn );
574}
575
576
577/**
578 * This returns a buffer (which was obtained from crNetAlloc()) back
579 * to the network layer so that it may be reused.
580 */
581void crNetFree( CRConnection *conn, void *buf )
582{
583 conn->Free( conn, buf );
584}
585
586
587void
588crInitMessageList(CRMessageList *list)
589{
590 list->head = list->tail = NULL;
591 list->numMessages = 0;
592#ifdef CHROMIUM_THREADSAFE
593 crInitMutex(&list->lock);
594 crInitCondition(&list->nonEmpty);
595#endif
596}
597
598
599/**
600 * Add a message node to the end of the message list.
601 * \param list the message list
602 * \param msg points to start of message buffer
603 * \param len length of message, in bytes
604 * \param conn connection associated with message (may be NULL)
605 */
606void
607crEnqueueMessage(CRMessageList *list, CRMessage *msg, unsigned int len,
608 CRConnection *conn)
609{
610 CRMessageListNode *node;
611
612#ifdef CHROMIUM_THREADSAFE
613 crLockMutex(&list->lock);
614#endif
615
616 node = (CRMessageListNode *) crAlloc(sizeof(CRMessageListNode));
617 node->mesg = msg;
618 node->len = len;
619 node->conn = conn;
620 node->next = NULL;
621
622 /* insert at tail */
623 if (list->tail)
624 list->tail->next = node;
625 else
626 list->head = node;
627 list->tail = node;
628
629 list->numMessages++;
630
631#ifdef CHROMIUM_THREADSAFE
632 crSignalCondition(&list->nonEmpty);
633 crUnlockMutex(&list->lock);
634#endif
635}
636
637
638/**
639 * Remove first message node from message list and return it.
640 * Don't block.
641 * \return 1 if message was dequeued, 0 otherwise.
642 */
643static int
644crDequeueMessageNoBlock(CRMessageList *list, CRMessage **msg,
645 unsigned int *len, CRConnection **conn)
646{
647 int retval;
648
649#ifdef CHROMIUM_THREADSAFE
650 crLockMutex(&list->lock);
651#endif
652
653 if (list->head) {
654 CRMessageListNode *node = list->head;
655
656 /* unlink the node */
657 list->head = node->next;
658 if (!list->head) {
659 /* empty list */
660 list->tail = NULL;
661 }
662
663 *msg = node->mesg;
664 *len = node->len;
665 if (conn)
666 *conn = node->conn;
667
668 list->numMessages--;
669
670 crFree(node);
671 retval = 1;
672 }
673 else {
674 *msg = NULL;
675 *len = 0;
676 retval = 0;
677 }
678
679#ifdef CHROMIUM_THREADSAFE
680 crUnlockMutex(&list->lock);
681#endif
682
683 return retval;
684}
685
686
687/**
688 * Remove message from tail of list. Block until non-empty if needed.
689 * \param list the message list
690 * \param msg returns start of message
691 * \param len returns message length, in bytes
692 * \param conn returns connection associated with message (may be NULL)
693 */
694void
695crDequeueMessage(CRMessageList *list, CRMessage **msg, unsigned int *len,
696 CRConnection **conn)
697{
698 CRMessageListNode *node;
699
700#ifdef CHROMIUM_THREADSAFE
701 crLockMutex(&list->lock);
702#endif
703
704#ifdef CHROMIUM_THREADSAFE
705 while (!list->head) {
706 crWaitCondition(&list->nonEmpty, &list->lock);
707 }
708#else
709 CRASSERT(list->head);
710#endif
711
712 node = list->head;
713
714 /* unlink the node */
715 list->head = node->next;
716 if (!list->head) {
717 /* empty list */
718 list->tail = NULL;
719 }
720
721 *msg = node->mesg;
722 CRASSERT((*msg)->header.type);
723 *len = node->len;
724 if (conn)
725 *conn = node->conn;
726
727 list->numMessages--;
728
729 crFree(node);
730
731#ifdef CHROMIUM_THREADSAFE
732 crUnlockMutex(&list->lock);
733#endif
734}
735
736
737
738/**
739 * Send a set of commands on a connection. Pretty straightforward, just
740 * error checking, byte counting, and a dispatch to the protocol's
741 * "send" implementation.
742 * The payload will be prefixed by a 4-byte length field.
743 *
744 * \param conn the network connection
745 * \param bufp if non-null the buffer was provided by the network layer
746 * and will be returned to the 'free' pool after it's sent.
747 * \param start points to first byte to send, which must point to a CRMessage
748 * object!
749 * \param len number of bytes to send
750 */
751void
752crNetSend(CRConnection *conn, void **bufp, const void *start, unsigned int len)
753{
754 CRMessage *msg = (CRMessage *) start;
755
756 CRASSERT( conn );
757 CRASSERT( len > 0 );
758 if ( bufp ) {
759 /* The region from [start .. start + len - 1] must lie inside the
760 * buffer pointed to by *bufp.
761 */
762 CRASSERT( start >= *bufp );
763 CRASSERT( (unsigned char *) start + len <=
764 (unsigned char *) *bufp + conn->buffer_size );
765 }
766
767#ifdef DEBUG
768 if ( conn->send_credits > CR_INITIAL_RECV_CREDITS )
769 {
770 crError( "crNetSend: send_credits=%u, looks like there is a leak (max=%u)",
771 conn->send_credits, CR_INITIAL_RECV_CREDITS );
772 }
773#endif
774
775 conn->total_bytes_sent += len;
776
777 msg->header.conn_id = conn->id;
778 conn->Send( conn, bufp, start, len );
779}
780
781
782/**
783 * Like crNetSend(), but the network layer is free to discard the data
784 * if something goes wrong. In particular, the UDP layer might discard
785 * the data in the event of transmission errors.
786 */
787void crNetBarf( CRConnection *conn, void **bufp,
788 const void *start, unsigned int len )
789{
790 CRMessage *msg = (CRMessage *) start;
791 CRASSERT( conn );
792 CRASSERT( len > 0 );
793 CRASSERT( conn->Barf );
794 if ( bufp ) {
795 CRASSERT( start >= *bufp );
796 CRASSERT( (unsigned char *) start + len <=
797 (unsigned char *) *bufp + conn->buffer_size );
798 }
799
800#ifdef DEBUG
801 if ( conn->send_credits > CR_INITIAL_RECV_CREDITS )
802 {
803 crError( "crNetBarf: send_credits=%u, looks like there is a "
804 "leak (max=%u)", conn->send_credits,
805 CR_INITIAL_RECV_CREDITS );
806 }
807#endif
808
809 conn->total_bytes_sent += len;
810
811 msg->header.conn_id = conn->id;
812 conn->Barf( conn, bufp, start, len );
813}
814
815
816/**
817 * Send a block of bytes across the connection without any sort of
818 * header/length information.
819 * \param conn the network connection
820 * \param buf points to first byte to send
821 * \param len number of bytes to send
822 */
823void crNetSendExact( CRConnection *conn, const void *buf, unsigned int len )
824{
825 CRASSERT(conn->SendExact);
826 conn->SendExact( conn, buf, len );
827}
828
829
830/**
831 * Connect to a server, as specified by the 'name' and 'buffer_size' fields
832 * of the CRNetServer parameter.
833 * When done, the CrNetServer's conn field will be initialized.
834 */
835void crNetServerConnect( CRNetServer *ns )
836{
837 ns->conn = crNetConnectToServer( ns->name, DEFAULT_SERVER_PORT,
838 ns->buffer_size, 0 );
839}
840
841
842/**
843 * Actually set up the specified connection.
844 * Apparently, this is only called from the crNetConnectToServer function.
845 */
846int crNetConnect( CRConnection *conn )
847{
848 return conn->Connect( conn );
849}
850
851
852/**
853 * Tear down a network connection (close the socket, etc).
854 */
855void crNetDisconnect( CRConnection *conn )
856{
857 conn->Disconnect( conn );
858 crFree( conn->hostname );
859#ifdef CHROMIUM_THREADSAFE
860 crFreeMutex( &conn->messageList.lock );
861#endif
862 crFree( conn );
863}
864
865
866/**
867 * Actually set up the specified connection.
868 * Apparently, this is only called from the crNetConnectToServer function.
869 */
870void crNetAccept( CRConnection *conn, const char *hostname, unsigned short port )
871{
872 conn->Accept( conn, hostname, port );
873}
874
875
876/**
877 * Do a blocking receive on a particular connection. This only
878 * really works for TCPIP, but it's really only used (right now) by
879 * the mothership client library.
880 * Read exactly the number of bytes specified (no headers/prefixes).
881 */
882void crNetSingleRecv( CRConnection *conn, void *buf, unsigned int len )
883{
884 if (conn->type != CR_TCPIP)
885 {
886 crError( "Can't do a crNetSingleReceive on anything other than TCPIP." );
887 }
888 conn->Recv( conn, buf, len );
889}
890
891
892/**
893 * Receive a chunk of a CR_MESSAGE_MULTI_BODY/TAIL transmission.
894 * \param conn the network connection
895 * \param msg the incoming multi-part message
896 * \param len number of bytes in the message
897 */
898static void
899crNetRecvMulti( CRConnection *conn, CRMessageMulti *msg, unsigned int len )
900{
901 CRMultiBuffer *multi = &(conn->multi);
902 unsigned char *src, *dst;
903
904 CRASSERT( len > sizeof(*msg) );
905 len -= sizeof(*msg);
906
907 /* Check if there's enough room in the multi-buffer to append 'len' bytes */
908 if ( len + multi->len > multi->max )
909 {
910 if ( multi->max == 0 )
911 {
912 multi->len = conn->sizeof_buffer_header;
913 multi->max = 8192; /* arbitrary initial size */
914 }
915 /* grow the buffer by 2x until it's big enough */
916 while ( len + multi->len > multi->max )
917 {
918 multi->max <<= 1;
919 }
920 crRealloc( &multi->buf, multi->max );
921 }
922
923 dst = (unsigned char *) multi->buf + multi->len;
924 src = (unsigned char *) msg + sizeof(*msg);
925 crMemcpy( dst, src, len );
926 multi->len += len;
927
928 if (msg->header.type == CR_MESSAGE_MULTI_TAIL)
929 {
930 /* OK, we've collected the last chunk of the multi-part message */
931 conn->HandleNewMessage(
932 conn,
933 (CRMessage *) (((char *) multi->buf) + conn->sizeof_buffer_header),
934 multi->len - conn->sizeof_buffer_header );
935
936 /* clean this up before calling the user */
937 multi->buf = NULL;
938 multi->len = 0;
939 multi->max = 0;
940 }
941
942 /* Don't do this too early! */
943 conn->InstantReclaim( conn, (CRMessage *) msg );
944}
945
946
947/**
948 * Increment the connection's send_credits by msg->credits.
949 */
950static void
951crNetRecvFlowControl( CRConnection *conn, CRMessageFlowControl *msg,
952 unsigned int len )
953{
954 CRASSERT( len == sizeof(CRMessageFlowControl) );
955 conn->send_credits += (conn->swap ? SWAP32(msg->credits) : msg->credits);
956 conn->InstantReclaim( conn, (CRMessage *) msg );
957}
958
959
960/**
961 * Called by the main receive function when we get a CR_MESSAGE_WRITEBACK
962 * message. Writeback is used to implement glGet*() functions.
963 */
964static void
965crNetRecvWriteback( CRMessageWriteback *wb )
966{
967 int *writeback;
968 crMemcpy( &writeback, &(wb->writeback_ptr), sizeof( writeback ) );
969 (*writeback)--;
970}
971
972
973/**
974 * Called by the main receive function when we get a CR_MESSAGE_READBACK
975 * message. Used to implement glGet*() functions.
976 */
977static void
978crNetRecvReadback( CRMessageReadback *rb, unsigned int len )
979{
980 /* minus the header, the destination pointer,
981 * *and* the implicit writeback pointer at the head. */
982
983 int payload_len = len - sizeof( *rb );
984 int *writeback;
985 void *dest_ptr;
986 crMemcpy( &writeback, &(rb->writeback_ptr), sizeof( writeback ) );
987 crMemcpy( &dest_ptr, &(rb->readback_ptr), sizeof( dest_ptr ) );
988
989 (*writeback)--;
990 crMemcpy( dest_ptr, ((char *)rb) + sizeof(*rb), payload_len );
991}
992
993
994/**
995 * This is used by the SPUs that do packing (such as Pack, Tilesort and
996 * Replicate) to process ReadPixels messages. We can't call this directly
997 * from the message loop below because the SPU's have other housekeeping
998 * to do for ReadPixels (such as decrementing counters).
999 */
1000void
1001crNetRecvReadPixels( const CRMessageReadPixels *rp, unsigned int len )
1002{
1003 int payload_len = len - sizeof( *rp );
1004 char *dest_ptr;
1005 const char *src_ptr = (const char *) rp + sizeof(*rp);
1006
1007 /* set dest_ptr value */
1008 crMemcpy( &(dest_ptr), &(rp->pixels), sizeof(dest_ptr));
1009
1010 /* store pixel data in app's memory */
1011 if (rp->alignment == 1 &&
1012 rp->skipRows == 0 &&
1013 rp->skipPixels == 0 &&
1014 (rp->rowLength == 0 || rp->rowLength == rp->width)) {
1015 /* no special packing is needed */
1016 crMemcpy( dest_ptr, src_ptr, payload_len );
1017 }
1018 else {
1019 /* need special packing */
1020 CRPixelPackState packing;
1021 packing.skipRows = rp->skipRows;
1022 packing.skipPixels = rp->skipPixels;
1023 packing.alignment = rp->alignment;
1024 packing.rowLength = rp->rowLength;
1025 packing.imageHeight = 0;
1026 packing.skipImages = 0;
1027 packing.swapBytes = GL_FALSE;
1028 packing.psLSBFirst = GL_FALSE;
1029 crPixelCopy2D( rp->width, rp->height,
1030 dest_ptr, rp->format, rp->type, &packing,
1031 src_ptr, rp->format, rp->type, /*unpacking*/NULL);
1032 }
1033}
1034
1035
1036
1037/**
1038 * If an incoming message is not consumed by any of the connection's
1039 * receive callbacks, this function will get called.
1040 *
1041 * XXX Make this function static???
1042 */
1043void
1044crNetDefaultRecv( CRConnection *conn, CRMessage *msg, unsigned int len )
1045{
1046 CRMessage *pRealMsg;
1047
1048 pRealMsg = (msg->header.type!=CR_MESSAGE_REDIR_PTR) ? msg : (CRMessage*) msg->redirptr.pMessage;
1049
1050 switch (pRealMsg->header.type)
1051 {
1052 case CR_MESSAGE_GATHER:
1053 break;
1054 case CR_MESSAGE_MULTI_BODY:
1055 case CR_MESSAGE_MULTI_TAIL:
1056 crNetRecvMulti( conn, &(pRealMsg->multi), len );
1057 return;
1058 case CR_MESSAGE_FLOW_CONTROL:
1059 crNetRecvFlowControl( conn, &(pRealMsg->flowControl), len );
1060 return;
1061 case CR_MESSAGE_OPCODES:
1062 case CR_MESSAGE_OOB:
1063 {
1064 /*CRMessageOpcodes *ops = (CRMessageOpcodes *) msg;
1065 *unsigned char *data_ptr = (unsigned char *) ops + sizeof( *ops) + ((ops->numOpcodes + 3 ) & ~0x03);
1066 *crDebugOpcodes( stdout, data_ptr-1, ops->numOpcodes ); */
1067 }
1068 break;
1069 case CR_MESSAGE_READ_PIXELS:
1070 crError( "Can't handle read pixels" );
1071 return;
1072 case CR_MESSAGE_WRITEBACK:
1073 crNetRecvWriteback( &(pRealMsg->writeback) );
1074 return;
1075 case CR_MESSAGE_READBACK:
1076 crNetRecvReadback( &(pRealMsg->readback), len );
1077 return;
1078 case CR_MESSAGE_CRUT:
1079 /* nothing */
1080 break;
1081 default:
1082 /* We can end up here if anything strange happens in
1083 * the GM layer. In particular, if the user tries to
1084 * send unpinned memory over GM it gets sent as all
1085 * 0xAA instead. This can happen when a program exits
1086 * ungracefully, so the GM is still DMAing memory as
1087 * it is disappearing out from under it. We can also
1088 * end up here if somebody adds a message type, and
1089 * doesn't put it in the above case block. That has
1090 * an obvious fix. */
1091 {
1092 char string[128];
1093 crBytesToString( string, sizeof(string), msg, len );
1094 crError("crNetDefaultRecv: received a bad message: type=%d buf=[%s]\n"
1095 "Did you add a new message type and forget to tell "
1096 "crNetDefaultRecv() about it?\n",
1097 msg->header.type, string );
1098 }
1099 }
1100
1101 /* If we make it this far, it's not a special message, so append it to
1102 * the end of the connection's list of received messages.
1103 */
1104 crEnqueueMessage(&conn->messageList, msg, len, conn);
1105}
1106
1107
1108/**
1109 * Default handler for receiving data. Called via crNetRecv().
1110 * Typically, the various implementations of the network layer call this.
1111 * \param msg this is the address of the message (of <len> bytes) the
1112 * first part of which is a CRMessage union.
1113 */
1114void
1115crNetDispatchMessage( CRNetReceiveFuncList *rfl, CRConnection *conn,
1116 CRMessage *msg, unsigned int len )
1117{
1118 for ( ; rfl ; rfl = rfl->next)
1119 {
1120 if (rfl->recv( conn, msg, len ))
1121 {
1122 /* Message was consumed by somebody (maybe a SPU).
1123 * All done.
1124 */
1125 return;
1126 }
1127 }
1128 /* Append the message to the connection's message list. It'll be
1129 * consumed later (by crNetPeekMessage or crNetGetMessage and
1130 * then freed with a call to crNetFree()). At this point, the buffer
1131 * *must* have been allocated with crNetAlloc!
1132 */
1133 crNetDefaultRecv( conn, msg, len );
1134}
1135
1136
1137/**
1138 * Return number of messages queued up on the given connection.
1139 */
1140int
1141crNetNumMessages(CRConnection *conn)
1142{
1143 return conn->messageList.numMessages;
1144}
1145
1146
1147/**
1148 * Get the next message in the connection's message list. These are
1149 * message that have already been received. We do not try to read more
1150 * bytes from the network connection.
1151 *
1152 * The crNetFree() function should be called when finished with the message!
1153 *
1154 * \param conn the network connection
1155 * \param message returns a pointer to the next message
1156 * \return length of message (header + payload, in bytes)
1157 */
1158unsigned int
1159crNetPeekMessage( CRConnection *conn, CRMessage **message )
1160{
1161 unsigned int len;
1162 CRConnection *dummyConn = NULL;
1163 if (crDequeueMessageNoBlock(&conn->messageList, message, &len, &dummyConn))
1164 return len;
1165 else
1166 return 0;
1167}
1168
1169
1170/**
1171 * Get the next message from the given network connection. If there isn't
1172 * one already in the linked list of received messages, call crNetRecv()
1173 * until we get something.
1174 *
1175 * \param message returns pointer to the message
1176 * \return total length of message (header + payload, in bytes)
1177 */
1178unsigned int
1179crNetGetMessage( CRConnection *conn, CRMessage **message )
1180{
1181 /* Keep getting work to do */
1182 for (;;)
1183 {
1184 int len = crNetPeekMessage( conn, message );
1185 if (len)
1186 return len;
1187 crNetRecv();
1188 }
1189
1190#if !defined(WINDOWS) && !defined(IRIX) && !defined(IRIX64)
1191 /* silence compiler */
1192 return 0;
1193#endif
1194}
1195
1196
1197/**
1198 * Read a \n-terminated string from a connection. Replace the \n with \0.
1199 * Useful for reading from the mothership.
1200 * \note This is an extremely inefficient way to read a string!
1201 *
1202 * \param conn the network connection
1203 * \param buf buffer in which to place results
1204 */
1205void crNetReadline( CRConnection *conn, void *buf )
1206{
1207 char *temp, c;
1208
1209 if (!conn || conn->type == CR_NO_CONNECTION)
1210 return;
1211
1212 if (conn->type != CR_TCPIP)
1213 {
1214 crError( "Can't do a crNetReadline on anything other than TCPIP (%d).",conn->type );
1215 }
1216 temp = (char*)buf;
1217 for (;;)
1218 {
1219 conn->Recv( conn, &c, 1 );
1220 if (c == '\n')
1221 {
1222 *temp = '\0';
1223 return;
1224 }
1225 *(temp++) = c;
1226 }
1227}
1228
1229/**
1230 * The big boy -- call this function to see (non-blocking) if there is
1231 * any pending work. If there is, the networking layer's "work received"
1232 * handler will be called, so this function only returns a flag. Work
1233 * is assumed to be placed on queues for processing by the handler.
1234 */
1235int crNetRecv( void )
1236{
1237 int found_work = 0;
1238
1239 if ( cr_net.use_tcpip )
1240 found_work += crTCPIPRecv();
1241#ifdef VBOX_WITH_HGCM
1242 if ( cr_net.use_hgcm )
1243 found_work += crVBoxHGCMRecv();
1244#endif
1245#ifdef SDP_SUPPORT
1246 if ( cr_net.use_sdp )
1247 found_work += crSDPRecv();
1248#endif
1249#ifdef IB_SUPPORT
1250 if ( cr_net.use_ib )
1251 found_work += crIBRecv();
1252#endif
1253 if ( cr_net.use_udp )
1254 found_work += crUDPTCPIPRecv();
1255
1256 if ( cr_net.use_file )
1257 found_work += crFileRecv();
1258
1259#ifdef GM_SUPPORT
1260 if ( cr_net.use_gm )
1261 found_work += crGmRecv();
1262#endif
1263
1264#ifdef TEAC_SUPPORT
1265 if ( cr_net.use_teac )
1266 found_work += crTeacRecv();
1267#endif
1268
1269#ifdef TCSCOMM_SUPPORT
1270 if ( cr_net.use_tcscomm )
1271 found_work += crTcscommRecv();
1272#endif
1273
1274 return found_work;
1275}
1276
1277
1278/**
1279 * Teac/TSComm only
1280 */
1281void
1282crNetSetRank( int my_rank )
1283{
1284 cr_net.my_rank = my_rank;
1285#ifdef TEAC_SUPPORT
1286 crTeacSetRank( cr_net.my_rank );
1287#endif
1288#ifdef TCSCOMM_SUPPORT
1289 crTcscommSetRank( cr_net.my_rank );
1290#endif
1291}
1292
1293/**
1294 * Teac/TSComm only
1295 */
1296void
1297crNetSetContextRange( int low_context, int high_context )
1298{
1299#ifdef TEAC_SUPPORT
1300 crTeacSetContextRange( low_context, high_context );
1301#endif
1302#ifdef TCSCOMM_SUPPORT
1303 crTcscommSetContextRange( low_context, high_context );
1304#endif
1305}
1306
1307/**
1308 * Teac/TSComm only
1309 */
1310void
1311crNetSetNodeRange( const char *low_node, const char *high_node )
1312{
1313#ifdef TEAC_SUPPORT
1314 crTeacSetNodeRange( low_node, high_node );
1315#endif
1316#ifdef TCSCOMM_SUPPORT
1317 crTcscommSetNodeRange( low_node, high_node );
1318#endif
1319}
1320
1321/**
1322 * Teac/TSComm only
1323 */
1324void
1325crNetSetKey( const unsigned char* key, const int keyLength )
1326{
1327#ifdef TEAC_SUPPORT
1328 crTeacSetKey( key, keyLength );
1329#endif
1330}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette