VirtualBox

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

Last change on this file since 15707 was 15532, checked in by vboxsync, 16 years ago

crOpenGL: export to OSE

  • 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 crFree( conn );
281 return NULL;
282 }
283
284 crDebug( "Done connecting to %s (swapping=%d)", server, conn->swap );
285 return conn;
286}
287
288
289/**
290 * Send a message to the receiver that another connection is needed.
291 * We send a CR_MESSAGE_NEWCLIENT packet, then call crNetServerConnect.
292 */
293void crNetNewClient( CRConnection *conn, CRNetServer *ns )
294{
295 unsigned int len = sizeof(CRMessageNewClient);
296 CRMessageNewClient msg;
297
298 CRASSERT( conn );
299
300 if (conn->swap)
301 msg.header.type = (CRMessageType) SWAP32(CR_MESSAGE_NEWCLIENT);
302 else
303 msg.header.type = CR_MESSAGE_NEWCLIENT;
304
305 crNetSend( conn, NULL, &msg, len );
306 crNetServerConnect( ns );
307}
308
309
310/**
311 * Accept a connection from a client.
312 * \param protocol the protocol to use (such as "tcpip" or "gm")
313 * \param hostname optional hostname of the expected client (may be NULL)
314 * \param port number of the port to accept on
315 * \param mtu maximum transmission unit
316 * \param broker either 1 or 0 to indicate if connection is brokered through
317 * the mothership
318 * \return new CRConnection object, or NULL
319 */
320CRConnection *
321crNetAcceptClient( const char *protocol, const char *hostname,
322 unsigned short port, unsigned int mtu, int broker )
323{
324 CRConnection *conn;
325
326 CRASSERT( cr_net.initialized );
327
328 conn = (CRConnection *) crCalloc( sizeof( *conn ) );
329 if (!conn)
330 return NULL;
331
332 /* init the non-zero fields */
333 conn->type = CR_NO_CONNECTION; /* we don't know yet */
334 conn->recv_credits = CR_INITIAL_RECV_CREDITS;
335 conn->port = port;
336 conn->mtu = mtu;
337 conn->buffer_size = mtu;
338 conn->broker = broker;
339 conn->endianness = crDetermineEndianness();
340 conn->teac_id = -1;
341 conn->teac_rank = -1;
342 conn->tcscomm_id = -1;
343 conn->tcscomm_rank = -1;
344
345 crInitMessageList(&conn->messageList);
346
347 /* now, just dispatch to the appropriate protocol's initialization functions. */
348 crDebug("In crNetAcceptClient( protocol=\"%s\" port=%d mtu=%d )",
349 protocol, (int) port, (int) mtu);
350
351 /* special case */
352 if ( !crStrncmp( protocol, "file", crStrlen( "file" ) ) ||
353 !crStrncmp( protocol, "swapfile", crStrlen( "swapfile" ) ) )
354 {
355 char filename[4096];
356 char protocol_only[4096];
357
358 cr_net.use_file++;
359 if (!crParseURL(protocol, protocol_only, filename, NULL, 0))
360 {
361 crError( "Malformed URL: \"%s\"", protocol );
362 }
363 conn->hostname = crStrdup( filename );
364
365 /* call the protocol-specific init routines */ // ktd (add)
366 InitConnection(conn, protocol_only, mtu); // ktd (add)
367 }
368 else {
369 /* call the protocol-specific init routines */
370 InitConnection(conn, protocol, mtu);
371 }
372
373 crNetAccept( conn, hostname, port );
374 return conn;
375}
376
377
378/**
379 * Close and free given connection.
380 */
381void
382crNetFreeConnection(CRConnection *conn)
383{
384 conn->Disconnect(conn);
385 crFree( conn->hostname );
386 #ifdef CHROMIUM_THREADSAFE
387 crFreeMutex( &conn->messageList.lock );
388 #endif
389 crFree(conn);
390}
391
392
393extern void __getHostInfo();
394/**
395 * Start the ball rolling. give functions to handle incoming traffic
396 * (usually placing blocks on a queue), and a handler for dropped
397 * connections.
398 */
399void crNetInit( CRNetReceiveFunc recvFunc, CRNetCloseFunc closeFunc )
400{
401 CRNetReceiveFuncList *rfl;
402 CRNetCloseFuncList *cfl;
403
404 if ( cr_net.initialized )
405 {
406 /*crDebug( "Networking already initialized!" );*/
407 }
408 else
409 {
410#ifdef WINDOWS
411 WORD wVersionRequested = MAKEWORD(2, 0);
412 WSADATA wsaData;
413 int err;
414
415 err = WSAStartup(wVersionRequested, &wsaData);
416 if (err != 0)
417 crError("Couldn't initialize sockets on WINDOWS");
418 //reinit hostname for debug messages as it's incorrect before WSAStartup gets called
419 __getHostInfo();
420#endif
421
422 cr_net.use_gm = 0;
423 cr_net.use_udp = 0;
424 cr_net.use_tcpip = 0;
425 cr_net.use_sdp = 0;
426 cr_net.use_tcscomm = 0;
427 cr_net.use_teac = 0;
428 cr_net.use_file = 0;
429 cr_net.use_hgcm = 0;
430 cr_net.num_clients = 0;
431#ifdef CHROMIUM_THREADSAFE
432 crInitMutex(&cr_net.mutex);
433#endif
434
435 cr_net.initialized = 1;
436 cr_net.recv_list = NULL;
437 cr_net.close_list = NULL;
438 }
439
440 if (recvFunc != NULL)
441 {
442 /* check if function is already in the list */
443 for (rfl = cr_net.recv_list ; rfl ; rfl = rfl->next )
444 {
445 if (rfl->recv == recvFunc)
446 {
447 /* we've already seen this function -- do nothing */
448 break;
449 }
450 }
451 /* not in list, so insert at the head */
452 if (!rfl)
453 {
454 rfl = (CRNetReceiveFuncList *) crAlloc( sizeof (*rfl ));
455 rfl->recv = recvFunc;
456 rfl->next = cr_net.recv_list;
457 cr_net.recv_list = rfl;
458 }
459 }
460
461 if (closeFunc != NULL)
462 {
463 /* check if function is already in the list */
464 for (cfl = cr_net.close_list ; cfl ; cfl = cfl->next )
465 {
466 if (cfl->close == closeFunc)
467 {
468 /* we've already seen this function -- do nothing */
469 break;
470 }
471 }
472 /* not in list, so insert at the head */
473 if (!cfl)
474 {
475 cfl = (CRNetCloseFuncList *) crAlloc( sizeof (*cfl ));
476 cfl->close = closeFunc;
477 cfl->next = cr_net.close_list;
478 cr_net.close_list = cfl;
479 }
480 }
481}
482
483/* Free up stuff */
484void crNetTearDown()
485{
486 CRNetReceiveFuncList *rfl;
487 CRNetCloseFuncList *cfl;
488 void *tmp;
489
490 if (!cr_net.initialized) return;
491
492#ifdef CHROMIUM_THREADSAFE
493 crLockMutex(&cr_net.mutex);
494#endif
495
496 /* Note, other protocols used by chromium should free up stuff too,
497 * but VBox doesn't use them, so no other checks.
498 */
499 if (cr_net.use_hgcm)
500 crVBoxHGCMTearDown();
501
502 for (rfl = cr_net.recv_list ; rfl ; rfl = (CRNetReceiveFuncList *) tmp )
503 {
504 tmp = rfl->next;
505 crFree(rfl);
506 }
507
508 for (cfl = cr_net.close_list ; cfl ; cfl = (CRNetCloseFuncList *) tmp )
509 {
510 tmp = cfl->next;
511 crFree(cfl);
512 }
513
514 cr_net.initialized = 0;
515
516#ifdef CHROMIUM_THREADSAFE
517 crUnlockMutex(&cr_net.mutex);
518 crFreeMutex(&cr_net.mutex);
519#endif
520}
521
522CRConnection** crNetDump( int* num )
523{
524 CRConnection **c;
525
526 c = crTCPIPDump( num );
527 if ( c ) return c;
528
529 c = crDevnullDump( num );
530 if ( c ) return c;
531
532 c = crFileDump( num );
533 if ( c ) return c;
534
535#ifdef VBOX_WITH_HGCM
536 c = crVBoxHGCMDump( num );
537 if ( c ) return c;
538#endif
539#ifdef GM_SUPPORT
540 c = crGmDump( num );
541 if ( c ) return c;
542#endif
543#ifdef IB_SUPPORT
544 c = crIBDump( num );
545 if ( c ) return c;
546#endif
547#ifdef SDP_SUPPORT
548 c = crSDPDump( num );
549 if ( c ) return c;
550#endif
551
552 *num = 0;
553 return NULL;
554}
555
556
557/*
558 * Allocate a network data buffer. The size will be the mtu size specified
559 * earlier to crNetConnectToServer() or crNetAcceptClient().
560 *
561 * Buffers that will eventually be transmitted on a connection
562 * *must* be allocated using this interface. This way, we can
563 * automatically pin memory and tag blocks, and we can also use
564 * our own buffer pool management.
565 */
566void *crNetAlloc( CRConnection *conn )
567{
568 CRASSERT( conn );
569 return conn->Alloc( conn );
570}
571
572
573/**
574 * This returns a buffer (which was obtained from crNetAlloc()) back
575 * to the network layer so that it may be reused.
576 */
577void crNetFree( CRConnection *conn, void *buf )
578{
579 conn->Free( conn, buf );
580}
581
582
583void
584crInitMessageList(CRMessageList *list)
585{
586 list->head = list->tail = NULL;
587 list->numMessages = 0;
588#ifdef CHROMIUM_THREADSAFE
589 crInitMutex(&list->lock);
590 crInitCondition(&list->nonEmpty);
591#endif
592}
593
594
595/**
596 * Add a message node to the end of the message list.
597 * \param list the message list
598 * \param msg points to start of message buffer
599 * \param len length of message, in bytes
600 * \param conn connection associated with message (may be NULL)
601 */
602void
603crEnqueueMessage(CRMessageList *list, CRMessage *msg, unsigned int len,
604 CRConnection *conn)
605{
606 CRMessageListNode *node;
607
608#ifdef CHROMIUM_THREADSAFE
609 crLockMutex(&list->lock);
610#endif
611
612 node = (CRMessageListNode *) crAlloc(sizeof(CRMessageListNode));
613 node->mesg = msg;
614 node->len = len;
615 node->conn = conn;
616 node->next = NULL;
617
618 /* insert at tail */
619 if (list->tail)
620 list->tail->next = node;
621 else
622 list->head = node;
623 list->tail = node;
624
625 list->numMessages++;
626
627#ifdef CHROMIUM_THREADSAFE
628 crSignalCondition(&list->nonEmpty);
629 crUnlockMutex(&list->lock);
630#endif
631}
632
633
634/**
635 * Remove first message node from message list and return it.
636 * Don't block.
637 * \return 1 if message was dequeued, 0 otherwise.
638 */
639static int
640crDequeueMessageNoBlock(CRMessageList *list, CRMessage **msg,
641 unsigned int *len, CRConnection **conn)
642{
643 int retval;
644
645#ifdef CHROMIUM_THREADSAFE
646 crLockMutex(&list->lock);
647#endif
648
649 if (list->head) {
650 CRMessageListNode *node = list->head;
651
652 /* unlink the node */
653 list->head = node->next;
654 if (!list->head) {
655 /* empty list */
656 list->tail = NULL;
657 }
658
659 *msg = node->mesg;
660 *len = node->len;
661 if (conn)
662 *conn = node->conn;
663
664 list->numMessages--;
665
666 crFree(node);
667 retval = 1;
668 }
669 else {
670 *msg = NULL;
671 *len = 0;
672 retval = 0;
673 }
674
675#ifdef CHROMIUM_THREADSAFE
676 crUnlockMutex(&list->lock);
677#endif
678
679 return retval;
680}
681
682
683/**
684 * Remove message from tail of list. Block until non-empty if needed.
685 * \param list the message list
686 * \param msg returns start of message
687 * \param len returns message length, in bytes
688 * \param conn returns connection associated with message (may be NULL)
689 */
690void
691crDequeueMessage(CRMessageList *list, CRMessage **msg, unsigned int *len,
692 CRConnection **conn)
693{
694 CRMessageListNode *node;
695
696#ifdef CHROMIUM_THREADSAFE
697 crLockMutex(&list->lock);
698#endif
699
700#ifdef CHROMIUM_THREADSAFE
701 while (!list->head) {
702 crWaitCondition(&list->nonEmpty, &list->lock);
703 }
704#else
705 CRASSERT(list->head);
706#endif
707
708 node = list->head;
709
710 /* unlink the node */
711 list->head = node->next;
712 if (!list->head) {
713 /* empty list */
714 list->tail = NULL;
715 }
716
717 *msg = node->mesg;
718 CRASSERT((*msg)->header.type);
719 *len = node->len;
720 if (conn)
721 *conn = node->conn;
722
723 list->numMessages--;
724
725 crFree(node);
726
727#ifdef CHROMIUM_THREADSAFE
728 crUnlockMutex(&list->lock);
729#endif
730}
731
732
733
734/**
735 * Send a set of commands on a connection. Pretty straightforward, just
736 * error checking, byte counting, and a dispatch to the protocol's
737 * "send" implementation.
738 * The payload will be prefixed by a 4-byte length field.
739 *
740 * \param conn the network connection
741 * \param bufp if non-null the buffer was provided by the network layer
742 * and will be returned to the 'free' pool after it's sent.
743 * \param start points to first byte to send, which must point to a CRMessage
744 * object!
745 * \param len number of bytes to send
746 */
747void
748crNetSend(CRConnection *conn, void **bufp, const void *start, unsigned int len)
749{
750 CRMessage *msg = (CRMessage *) start;
751
752 CRASSERT( conn );
753 CRASSERT( len > 0 );
754 if ( bufp ) {
755 /* The region from [start .. start + len - 1] must lie inside the
756 * buffer pointed to by *bufp.
757 */
758 CRASSERT( start >= *bufp );
759 CRASSERT( (unsigned char *) start + len <=
760 (unsigned char *) *bufp + conn->buffer_size );
761 }
762
763#ifndef NDEBUG
764 if ( conn->send_credits > CR_INITIAL_RECV_CREDITS )
765 {
766 crError( "crNetSend: send_credits=%u, looks like there is a leak (max=%u)",
767 conn->send_credits, CR_INITIAL_RECV_CREDITS );
768 }
769#endif
770
771 conn->total_bytes_sent += len;
772
773 msg->header.conn_id = conn->id;
774 conn->Send( conn, bufp, start, len );
775}
776
777
778/**
779 * Like crNetSend(), but the network layer is free to discard the data
780 * if something goes wrong. In particular, the UDP layer might discard
781 * the data in the event of transmission errors.
782 */
783void crNetBarf( CRConnection *conn, void **bufp,
784 const void *start, unsigned int len )
785{
786 CRMessage *msg = (CRMessage *) start;
787 CRASSERT( conn );
788 CRASSERT( len > 0 );
789 CRASSERT( conn->Barf );
790 if ( bufp ) {
791 CRASSERT( start >= *bufp );
792 CRASSERT( (unsigned char *) start + len <=
793 (unsigned char *) *bufp + conn->buffer_size );
794 }
795
796#ifndef NDEBUG
797 if ( conn->send_credits > CR_INITIAL_RECV_CREDITS )
798 {
799 crError( "crNetBarf: send_credits=%u, looks like there is a "
800 "leak (max=%u)", conn->send_credits,
801 CR_INITIAL_RECV_CREDITS );
802 }
803#endif
804
805 conn->total_bytes_sent += len;
806
807 msg->header.conn_id = conn->id;
808 conn->Barf( conn, bufp, start, len );
809}
810
811
812/**
813 * Send a block of bytes across the connection without any sort of
814 * header/length information.
815 * \param conn the network connection
816 * \param buf points to first byte to send
817 * \param len number of bytes to send
818 */
819void crNetSendExact( CRConnection *conn, const void *buf, unsigned int len )
820{
821 CRASSERT(conn->SendExact);
822 conn->SendExact( conn, buf, len );
823}
824
825
826/**
827 * Connect to a server, as specified by the 'name' and 'buffer_size' fields
828 * of the CRNetServer parameter.
829 * When done, the CrNetServer's conn field will be initialized.
830 */
831void crNetServerConnect( CRNetServer *ns )
832{
833 ns->conn = crNetConnectToServer( ns->name, DEFAULT_SERVER_PORT,
834 ns->buffer_size, 0 );
835}
836
837
838/**
839 * Actually set up the specified connection.
840 * Apparently, this is only called from the crNetConnectToServer function.
841 */
842int crNetConnect( CRConnection *conn )
843{
844 return conn->Connect( conn );
845}
846
847
848/**
849 * Tear down a network connection (close the socket, etc).
850 */
851void crNetDisconnect( CRConnection *conn )
852{
853 conn->Disconnect( conn );
854 crFree( conn->hostname );
855#ifdef CHROMIUM_THREADSAFE
856 crFreeMutex( &conn->messageList.lock );
857#endif
858 crFree( conn );
859}
860
861
862/**
863 * Actually set up the specified connection.
864 * Apparently, this is only called from the crNetConnectToServer function.
865 */
866void crNetAccept( CRConnection *conn, const char *hostname, unsigned short port )
867{
868 conn->Accept( conn, hostname, port );
869}
870
871
872/**
873 * Do a blocking receive on a particular connection. This only
874 * really works for TCPIP, but it's really only used (right now) by
875 * the mothership client library.
876 * Read exactly the number of bytes specified (no headers/prefixes).
877 */
878void crNetSingleRecv( CRConnection *conn, void *buf, unsigned int len )
879{
880 if (conn->type != CR_TCPIP)
881 {
882 crError( "Can't do a crNetSingleReceive on anything other than TCPIP." );
883 }
884 conn->Recv( conn, buf, len );
885}
886
887
888/**
889 * Receive a chunk of a CR_MESSAGE_MULTI_BODY/TAIL transmission.
890 * \param conn the network connection
891 * \param msg the incoming multi-part message
892 * \param len number of bytes in the message
893 */
894static void
895crNetRecvMulti( CRConnection *conn, CRMessageMulti *msg, unsigned int len )
896{
897 CRMultiBuffer *multi = &(conn->multi);
898 unsigned char *src, *dst;
899
900 CRASSERT( len > sizeof(*msg) );
901 len -= sizeof(*msg);
902
903 /* Check if there's enough room in the multi-buffer to append 'len' bytes */
904 if ( len + multi->len > multi->max )
905 {
906 if ( multi->max == 0 )
907 {
908 multi->len = conn->sizeof_buffer_header;
909 multi->max = 8192; /* arbitrary initial size */
910 }
911 /* grow the buffer by 2x until it's big enough */
912 while ( len + multi->len > multi->max )
913 {
914 multi->max <<= 1;
915 }
916 crRealloc( &multi->buf, multi->max );
917 }
918
919 dst = (unsigned char *) multi->buf + multi->len;
920 src = (unsigned char *) msg + sizeof(*msg);
921 crMemcpy( dst, src, len );
922 multi->len += len;
923
924 if (msg->header.type == CR_MESSAGE_MULTI_TAIL)
925 {
926 /* OK, we've collected the last chunk of the multi-part message */
927 conn->HandleNewMessage(
928 conn,
929 (CRMessage *) (((char *) multi->buf) + conn->sizeof_buffer_header),
930 multi->len - conn->sizeof_buffer_header );
931
932 /* clean this up before calling the user */
933 multi->buf = NULL;
934 multi->len = 0;
935 multi->max = 0;
936 }
937
938 /* Don't do this too early! */
939 conn->InstantReclaim( conn, (CRMessage *) msg );
940}
941
942
943/**
944 * Increment the connection's send_credits by msg->credits.
945 */
946static void
947crNetRecvFlowControl( CRConnection *conn, CRMessageFlowControl *msg,
948 unsigned int len )
949{
950 CRASSERT( len == sizeof(CRMessageFlowControl) );
951 conn->send_credits += (conn->swap ? SWAP32(msg->credits) : msg->credits);
952 conn->InstantReclaim( conn, (CRMessage *) msg );
953}
954
955
956/**
957 * Called by the main receive function when we get a CR_MESSAGE_WRITEBACK
958 * message. Writeback is used to implement glGet*() functions.
959 */
960static void
961crNetRecvWriteback( CRMessageWriteback *wb )
962{
963 int *writeback;
964 crMemcpy( &writeback, &(wb->writeback_ptr), sizeof( writeback ) );
965 (*writeback)--;
966}
967
968
969/**
970 * Called by the main receive function when we get a CR_MESSAGE_READBACK
971 * message. Used to implement glGet*() functions.
972 */
973static void
974crNetRecvReadback( CRMessageReadback *rb, unsigned int len )
975{
976 /* minus the header, the destination pointer,
977 * *and* the implicit writeback pointer at the head. */
978
979 int payload_len = len - sizeof( *rb );
980 int *writeback;
981 void *dest_ptr;
982 crMemcpy( &writeback, &(rb->writeback_ptr), sizeof( writeback ) );
983 crMemcpy( &dest_ptr, &(rb->readback_ptr), sizeof( dest_ptr ) );
984
985 (*writeback)--;
986 crMemcpy( dest_ptr, ((char *)rb) + sizeof(*rb), payload_len );
987}
988
989
990/**
991 * This is used by the SPUs that do packing (such as Pack, Tilesort and
992 * Replicate) to process ReadPixels messages. We can't call this directly
993 * from the message loop below because the SPU's have other housekeeping
994 * to do for ReadPixels (such as decrementing counters).
995 */
996void
997crNetRecvReadPixels( const CRMessageReadPixels *rp, unsigned int len )
998{
999 int payload_len = len - sizeof( *rp );
1000 char *dest_ptr;
1001 const char *src_ptr = (const char *) rp + sizeof(*rp);
1002
1003 /* set dest_ptr value */
1004 crMemcpy( &(dest_ptr), &(rp->pixels), sizeof(dest_ptr));
1005
1006 /* store pixel data in app's memory */
1007 if (rp->alignment == 1 &&
1008 rp->skipRows == 0 &&
1009 rp->skipPixels == 0 &&
1010 (rp->rowLength == 0 || rp->rowLength == rp->width)) {
1011 /* no special packing is needed */
1012 crMemcpy( dest_ptr, src_ptr, payload_len );
1013 }
1014 else {
1015 /* need special packing */
1016 CRPixelPackState packing;
1017 packing.skipRows = rp->skipRows;
1018 packing.skipPixels = rp->skipPixels;
1019 packing.alignment = rp->alignment;
1020 packing.rowLength = rp->rowLength;
1021 packing.imageHeight = 0;
1022 packing.skipImages = 0;
1023 packing.swapBytes = GL_FALSE;
1024 packing.psLSBFirst = GL_FALSE;
1025 crPixelCopy2D( rp->width, rp->height,
1026 dest_ptr, rp->format, rp->type, &packing,
1027 src_ptr, rp->format, rp->type, /*unpacking*/NULL);
1028 }
1029}
1030
1031
1032
1033/**
1034 * If an incoming message is not consumed by any of the connection's
1035 * receive callbacks, this function will get called.
1036 *
1037 * XXX Make this function static???
1038 */
1039void
1040crNetDefaultRecv( CRConnection *conn, CRMessage *msg, unsigned int len )
1041{
1042 CRMessage *pRealMsg;
1043
1044 pRealMsg = (msg->header.type!=CR_MESSAGE_REDIR_PTR) ? msg : (CRMessage*) msg->redirptr.pMessage;
1045
1046 switch (pRealMsg->header.type)
1047 {
1048 case CR_MESSAGE_GATHER:
1049 break;
1050 case CR_MESSAGE_MULTI_BODY:
1051 case CR_MESSAGE_MULTI_TAIL:
1052 crNetRecvMulti( conn, &(pRealMsg->multi), len );
1053 return;
1054 case CR_MESSAGE_FLOW_CONTROL:
1055 crNetRecvFlowControl( conn, &(pRealMsg->flowControl), len );
1056 return;
1057 case CR_MESSAGE_OPCODES:
1058 case CR_MESSAGE_OOB:
1059 {
1060 /*CRMessageOpcodes *ops = (CRMessageOpcodes *) msg;
1061 *unsigned char *data_ptr = (unsigned char *) ops + sizeof( *ops) + ((ops->numOpcodes + 3 ) & ~0x03);
1062 *crDebugOpcodes( stdout, data_ptr-1, ops->numOpcodes ); */
1063 }
1064 break;
1065 case CR_MESSAGE_READ_PIXELS:
1066 crError( "Can't handle read pixels" );
1067 return;
1068 case CR_MESSAGE_WRITEBACK:
1069 crNetRecvWriteback( &(pRealMsg->writeback) );
1070 return;
1071 case CR_MESSAGE_READBACK:
1072 crNetRecvReadback( &(pRealMsg->readback), len );
1073 return;
1074 case CR_MESSAGE_CRUT:
1075 /* nothing */
1076 break;
1077 default:
1078 /* We can end up here if anything strange happens in
1079 * the GM layer. In particular, if the user tries to
1080 * send unpinned memory over GM it gets sent as all
1081 * 0xAA instead. This can happen when a program exits
1082 * ungracefully, so the GM is still DMAing memory as
1083 * it is disappearing out from under it. We can also
1084 * end up here if somebody adds a message type, and
1085 * doesn't put it in the above case block. That has
1086 * an obvious fix. */
1087 {
1088 char string[128];
1089 crBytesToString( string, sizeof(string), msg, len );
1090 crError("crNetDefaultRecv: received a bad message: type=%d buf=[%s]\n"
1091 "Did you add a new message type and forget to tell "
1092 "crNetDefaultRecv() about it?\n",
1093 msg->header.type, string );
1094 }
1095 }
1096
1097 /* If we make it this far, it's not a special message, so append it to
1098 * the end of the connection's list of received messages.
1099 */
1100 crEnqueueMessage(&conn->messageList, msg, len, conn);
1101}
1102
1103
1104/**
1105 * Default handler for receiving data. Called via crNetRecv().
1106 * Typically, the various implementations of the network layer call this.
1107 * \param msg this is the address of the message (of <len> bytes) the
1108 * first part of which is a CRMessage union.
1109 */
1110void
1111crNetDispatchMessage( CRNetReceiveFuncList *rfl, CRConnection *conn,
1112 CRMessage *msg, unsigned int len )
1113{
1114 for ( ; rfl ; rfl = rfl->next)
1115 {
1116 if (rfl->recv( conn, msg, len ))
1117 {
1118 /* Message was consumed by somebody (maybe a SPU).
1119 * All done.
1120 */
1121 return;
1122 }
1123 }
1124 /* Append the message to the connection's message list. It'll be
1125 * consumed later (by crNetPeekMessage or crNetGetMessage and
1126 * then freed with a call to crNetFree()). At this point, the buffer
1127 * *must* have been allocated with crNetAlloc!
1128 */
1129 crNetDefaultRecv( conn, msg, len );
1130}
1131
1132
1133/**
1134 * Return number of messages queued up on the given connection.
1135 */
1136int
1137crNetNumMessages(CRConnection *conn)
1138{
1139 return conn->messageList.numMessages;
1140}
1141
1142
1143/**
1144 * Get the next message in the connection's message list. These are
1145 * message that have already been received. We do not try to read more
1146 * bytes from the network connection.
1147 *
1148 * The crNetFree() function should be called when finished with the message!
1149 *
1150 * \param conn the network connection
1151 * \param message returns a pointer to the next message
1152 * \return length of message (header + payload, in bytes)
1153 */
1154unsigned int
1155crNetPeekMessage( CRConnection *conn, CRMessage **message )
1156{
1157 unsigned int len;
1158 CRConnection *dummyConn = NULL;
1159 if (crDequeueMessageNoBlock(&conn->messageList, message, &len, &dummyConn))
1160 return len;
1161 else
1162 return 0;
1163}
1164
1165
1166/**
1167 * Get the next message from the given network connection. If there isn't
1168 * one already in the linked list of received messages, call crNetRecv()
1169 * until we get something.
1170 *
1171 * \param message returns pointer to the message
1172 * \return total length of message (header + payload, in bytes)
1173 */
1174unsigned int
1175crNetGetMessage( CRConnection *conn, CRMessage **message )
1176{
1177 /* Keep getting work to do */
1178 for (;;)
1179 {
1180 int len = crNetPeekMessage( conn, message );
1181 if (len)
1182 return len;
1183 crNetRecv();
1184 }
1185
1186#if !defined(WINDOWS) && !defined(IRIX) && !defined(IRIX64)
1187 /* silence compiler */
1188 return 0;
1189#endif
1190}
1191
1192
1193/**
1194 * Read a \n-terminated string from a connection. Replace the \n with \0.
1195 * Useful for reading from the mothership.
1196 * \note This is an extremely inefficient way to read a string!
1197 *
1198 * \param conn the network connection
1199 * \param buf buffer in which to place results
1200 */
1201void crNetReadline( CRConnection *conn, void *buf )
1202{
1203 char *temp, c;
1204
1205 if (!conn || conn->type == CR_NO_CONNECTION)
1206 return;
1207
1208 if (conn->type != CR_TCPIP)
1209 {
1210 crError( "Can't do a crNetReadline on anything other than TCPIP (%d).",conn->type );
1211 }
1212 temp = (char*)buf;
1213 for (;;)
1214 {
1215 conn->Recv( conn, &c, 1 );
1216 if (c == '\n')
1217 {
1218 *temp = '\0';
1219 return;
1220 }
1221 *(temp++) = c;
1222 }
1223}
1224
1225/**
1226 * The big boy -- call this function to see (non-blocking) if there is
1227 * any pending work. If there is, the networking layer's "work received"
1228 * handler will be called, so this function only returns a flag. Work
1229 * is assumed to be placed on queues for processing by the handler.
1230 */
1231int crNetRecv( void )
1232{
1233 int found_work = 0;
1234
1235 if ( cr_net.use_tcpip )
1236 found_work += crTCPIPRecv();
1237#ifdef VBOX_WITH_HGCM
1238 if ( cr_net.use_hgcm )
1239 found_work += crVBoxHGCMRecv();
1240#endif
1241#ifdef SDP_SUPPORT
1242 if ( cr_net.use_sdp )
1243 found_work += crSDPRecv();
1244#endif
1245#ifdef IB_SUPPORT
1246 if ( cr_net.use_ib )
1247 found_work += crIBRecv();
1248#endif
1249 if ( cr_net.use_udp )
1250 found_work += crUDPTCPIPRecv();
1251
1252 if ( cr_net.use_file )
1253 found_work += crFileRecv();
1254
1255#ifdef GM_SUPPORT
1256 if ( cr_net.use_gm )
1257 found_work += crGmRecv();
1258#endif
1259
1260#ifdef TEAC_SUPPORT
1261 if ( cr_net.use_teac )
1262 found_work += crTeacRecv();
1263#endif
1264
1265#ifdef TCSCOMM_SUPPORT
1266 if ( cr_net.use_tcscomm )
1267 found_work += crTcscommRecv();
1268#endif
1269
1270 return found_work;
1271}
1272
1273
1274/**
1275 * Teac/TSComm only
1276 */
1277void
1278crNetSetRank( int my_rank )
1279{
1280 cr_net.my_rank = my_rank;
1281#ifdef TEAC_SUPPORT
1282 crTeacSetRank( cr_net.my_rank );
1283#endif
1284#ifdef TCSCOMM_SUPPORT
1285 crTcscommSetRank( cr_net.my_rank );
1286#endif
1287}
1288
1289/**
1290 * Teac/TSComm only
1291 */
1292void
1293crNetSetContextRange( int low_context, int high_context )
1294{
1295#ifdef TEAC_SUPPORT
1296 crTeacSetContextRange( low_context, high_context );
1297#endif
1298#ifdef TCSCOMM_SUPPORT
1299 crTcscommSetContextRange( low_context, high_context );
1300#endif
1301}
1302
1303/**
1304 * Teac/TSComm only
1305 */
1306void
1307crNetSetNodeRange( const char *low_node, const char *high_node )
1308{
1309#ifdef TEAC_SUPPORT
1310 crTeacSetNodeRange( low_node, high_node );
1311#endif
1312#ifdef TCSCOMM_SUPPORT
1313 crTcscommSetNodeRange( low_node, high_node );
1314#endif
1315}
1316
1317/**
1318 * Teac/TSComm only
1319 */
1320void
1321crNetSetKey( const unsigned char* key, const int keyLength )
1322{
1323#ifdef TEAC_SUPPORT
1324 crTeacSetKey( key, keyLength );
1325#endif
1326}
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