VirtualBox

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

Last change on this file since 18068 was 15759, checked in by vboxsync, 16 years ago

crOpenGL: partial fix for multithreaded guest apps (3457)

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