Source

gb_emulator / gb_emulator / src / gb_comms_serial.cpp

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

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#include <gb_emulator/gb_comms_serial.h>

#include <assert.h>

#include <iomanip>
#include <iostream>
#include <limits>

#include <boost/date_time/posix_time/posix_time.hpp>

#include <gb_net/tcp_client.h>
#include <gb_net/tcp_server.h>

#include <gb_emulator/constants.hpp>
#include <gb_emulator/gb.hpp>
#include <gb_emulator/gb_memory.hpp>

namespace bs = boost::system;
namespace io = boost::asio;
namespace pt = boost::posix_time;
using namespace gbnet;
using boost::asio::ip::tcp;
using std::basic_string;
using std::clog;
using std::hex;
using std::numeric_limits;
using std::setw;
using std::setfill;
using std::string;

// Syncronisation pulse message ID
static const uint16_t SYNC_ID = 0xbe10;

GbCommsSerial::GbCommsSerial(Gb &gb, int &cycles):
gb_(gb),
cycles_(cycles),
state_(STATE_IDLE),
connected_(false),
server_(false),
lineState_(true),
sequence_(0)
{
}

GbCommsSerial::GbCommsSerial(Gb &gb, int &cycles, io::io_service &ioService, uint16_t port):
gb_(gb),
cycles_(cycles),
connected_(false),
server_(true),
net_(new TcpServer(ioService, port))
{
	reset();
	connectNetworkSignals();
}

GbCommsSerial::GbCommsSerial(Gb &gb, int &cycles, io::io_service &ioService, const string &host,
	uint16_t port):
gb_(gb),
cycles_(cycles),
connected_(false),
server_(false),
net_(new TcpClient(ioService, host, port))
{
	reset();
	connectNetworkSignals();
}

void GbCommsSerial::reset()
{
	state_ = STATE_IDLE;
	intDelay_.reset();
	lineState_ = true;
	sequence_ = 0;
	data_ = 0;
}

void GbCommsSerial::poll()
{
	switch (state_)
	{
	case STATE_INT_WAIT_NO_DATA:
		// No data received in time; pause the emulator
		state_ = STATE_INT_WAIT_PAUSED;
		gb_.cpu_->pause = true;
		break;

	case STATE_EXT_WAIT_NO_DATA:
		// No data received in time; don't need to do anything else but wait silently
		state_ = STATE_EXT_WAIT_TIMEOUT;
		break;

	case STATE_INT_WAIT_DATA:
	case STATE_EXT_WAIT_DATA:
		// Data arrived in time; return it to the program
		state_ = STATE_IDLE;
		gb_.mem_->ioPorts()[SB]  = data_;
		gb_.mem_->ioPorts()[SC] &= ~0x80;
		gb_.mem_->ioPorts()[IF] |= SERIAL_INTR;
		break;

	case STATE_EXT_WAIT_DATA_WITH_DELAY:
		// Data arrived and another internal clock request was received
		assert(intDelay_);
		state_ = STATE_INT_DELAY;
		cycles_ = SERIAL_DELAY_ALLOWANCE;
		gb_.mem_->ioPorts()[SB]  = data_;
		gb_.mem_->ioPorts()[SC] &= ~0x80;
		gb_.mem_->ioPorts()[IF] |= SERIAL_INTR;
		break;

	case STATE_INT_DELAY:
		// An internal clock request was received but the program is still not ready to handle it;
		// send back a negative response
		clog << pt::microsec_clock::local_time() << ": An internal clock request was received but "
		        "an external clock request was not made in time\n";
		state_ = STATE_IDLE;

		SerialDataMessage response;
		response.sequence = intDelay_->sequence;
		response.data = lineState_ ? 0xff : 0x00;

		intDelay_.reset();
		net_->postMessage(SerialDataMessage::TYPE_INACTIVE,
			basic_string<uint8_t>(reinterpret_cast<uint8_t *>(&response), sizeof(response)));
		break;

	default:
		assert(!"invalid state");
	}
}

void GbCommsSerial::writeIoPort(uint8_t ptr, uint8_t val)
{
	// This function shouldn't ever be called if the emulator is paused
	assert(state_ != STATE_INT_WAIT_PAUSED);

	switch (ptr)
	{
	case SB:
		gb_.mem_->ioPorts()[ptr] = val;
		break;

	case SC:
		// Bit 1 is not accessible in DMG mode
		if (gb_.gbc_)
		{
			gb_.mem_->ioPorts()[ptr] = val & 0x83;
		}
		else
		{
			gb_.mem_->ioPorts()[ptr] = val & 0x81;
		}

		// Make a note if the transfer is being abandoned after data has already been sent because
		// that is likely to cause problems
		if (state_ == STATE_EXT_WAIT_DATA || state_ == STATE_INT_WAIT_DATA ||
			state_ == STATE_EXT_WAIT_DATA_WITH_DELAY)
		{
			clog << pt::microsec_clock::local_time() << ": Abandoning transfer after data has "
			        "already been sent\n";
		}

		// Start the transfer if necessary
		if (val & 0x80)
		{
			// Send the request to the remote host if we are connected
			if (connected_)
			{
				if (gb_.mem_->ioPorts()[SC] & 0x01)
				{
					// Internal clock
					if (state_ == STATE_INT_DELAY || state_ == STATE_EXT_WAIT_DATA_WITH_DELAY)
					{
						// Send a negative response to the internal clock request
						clog << pt::microsec_clock::local_time() << ": An internal clock request "
						        "was received but it was rejected because the program made its own "
						        "internal clock request\n";

						SerialDataMessage response;
						response.sequence = intDelay_->sequence;
						response.data = lineState_ ? 0xff : 0x00;

						intDelay_.reset();
						net_->postMessage(SerialDataMessage::TYPE_INACTIVE,
							basic_string<uint8_t>(reinterpret_cast<uint8_t *>(&response), sizeof(response)));
					}

					state_ = STATE_INT_WAIT_NO_DATA;

					SerialDataMessage message;
					message.sequence = ++sequence_;
					message.data = gb_.mem_->ioPorts()[SB];
					lineState_ = message.data & 0x01;
					
					net_->postMessage(SerialDataMessage::TYPE_INT,
						basic_string<uint8_t>(reinterpret_cast<uint8_t *>(&message), sizeof(message)));
				}
				else
				{
					// External clock
					if (state_ == STATE_INT_DELAY || state_ == STATE_EXT_WAIT_DATA_WITH_DELAY)
					{
						// Send a response to the delayed internal clock request
						SerialDataMessage response;
						response.sequence = intDelay_->sequence;
						response.data = gb_.mem_->ioPorts()[SB];

						net_->postMessage(SerialDataMessage::TYPE_DATA,
							basic_string<uint8_t>(reinterpret_cast<uint8_t *>(&response), sizeof(response)));

						// Save the received value
						state_ = STATE_EXT_WAIT_DATA;
						data_ = intDelay_->data;
						intDelay_.reset();
					}
					else
					{
						state_ = STATE_EXT_WAIT_NO_DATA;
						data_ = gb_.mem_->ioPorts()[SB];
					}
				}
			}
			else
			{
				if (gb_.mem_->ioPorts()[SC] & 0x01)
				{
					// Set the received data to 0xff to indicate there is no connection
					state_ = STATE_INT_WAIT_DATA;
					data_ = 0xff;
				}
				else
				{
					// Nothing to do
					state_ = STATE_EXT_WAIT_NO_DATA;
				}
			}

			// Request a callback for when the transfer period has elapsed
			if (gb_.gbc_ && (gb_.mem_->ioPorts()[SC] & 0x02))
			{
				cycles_ = SERIAL2_CYCLES;
			}
			else
			{
				cycles_ = SERIAL1_CYCLES;
			}
		}
		else
		{
			// Cancel transfer
			if (state_ == STATE_EXT_WAIT_DATA_WITH_DELAY)
			{
				state_ = STATE_INT_DELAY;
				cycles_ = SERIAL_DELAY_ALLOWANCE;
			}
			else if (state_ != STATE_INT_DELAY)
			{
				state_ = STATE_IDLE;
				cycles_ = numeric_limits<int>::max();
			}
		}

		break;
	}
}

void GbCommsSerial::synchronise()
{
	if (connected_ && server_)
	{
		net_->postMessage(SYNC_ID, basic_string<uint8_t>());
	}
}

void GbCommsSerial::connectNetworkSignals()
{
	onListeningConnection_ = net_->onListening(boost::bind(&GbCommsSerial::onListening, this, _1));
	onConnectedConnection_ = net_->onConnected(boost::bind(&GbCommsSerial::onConnected, this, _1));
	onMessageReceivedConnection_ = net_->onMessageReceived(
		boost::bind(&GbCommsSerial::onMessageReceived, this, _1, _2));
	onBadPacketConnection_ = net_->onBadPacket(boost::bind(&GbCommsSerial::onBadPacket, this));
	onNetworkErrorConnection_ = net_->onNetworkError(
		boost::bind(&GbCommsSerial::onNetworkError, this, _1, _2));
}

void GbCommsSerial::onListening(const tcp::endpoint &endpoint)
{
	clog << pt::microsec_clock::local_time() << ": Server listening on " << endpoint << "\n";
}

void GbCommsSerial::onConnected(const tcp::endpoint &endpoint)
{
	clog << pt::microsec_clock::local_time() << ": Connection established to " << endpoint << "\n";
	connected_ = true;

	if (!server_)
	{
		// Switch to the remote clock if we are a client
		gb_.clockSource_ = Gb::CLOCK_REMOTE;
	}
}

void GbCommsSerial::onMessageReceived(uint16_t identifier, const basic_string<uint8_t> &message)
{
	if ((identifier < SerialDataMessage::TYPE_MAX && message.size() != sizeof(SerialDataMessage)) ||
		(identifier == SYNC_ID && !message.empty()))
	{
		clog << pt::microsec_clock::local_time()
		     << ": Data message received with incorrect length\n";
		return;
	}
	const SerialDataMessage *data = reinterpret_cast<const SerialDataMessage *>(message.data());

	switch (identifier)
	{
	case SerialDataMessage::TYPE_INT:
		switch (state_)
		{
		case STATE_EXT_WAIT_NO_DATA:
			{
				// Send our data back
				SerialDataMessage response;
				response.sequence = data->sequence;
				response.data = data_;
				lineState_ = data_ & 0x01;

				net_->postMessage(SerialDataMessage::TYPE_DATA,
					basic_string<uint8_t>(reinterpret_cast<uint8_t *>(&response),
					sizeof(response)));

				// Save the received data
				state_ = STATE_EXT_WAIT_DATA;
				data_ = data->data;
			}
			break;

		case STATE_EXT_WAIT_TIMEOUT:
			{
				// Send our data back
				SerialDataMessage response;
				response.sequence = data->sequence;
				response.data = data_;
				lineState_ = data_ & 0x01;

				net_->postMessage(SerialDataMessage::TYPE_DATA,
					basic_string<uint8_t>(reinterpret_cast<uint8_t *>(&response),
					sizeof(response)));

				// Save the received data
				state_ = STATE_IDLE;
				gb_.mem_->ioPorts()[SB]  = data->data;
				gb_.mem_->ioPorts()[SC] &= ~0x80;
				gb_.mem_->ioPorts()[IF] |= SERIAL_INTR;
			}
			break;

		case STATE_IDLE:
		case STATE_INT_DELAY:
			// Allow the program some time to make an external clock request before sending a
			// negative response
			if (state_ == STATE_INT_DELAY)
			{
				clog << pt::microsec_clock::local_time() << ": Another internal clock request was "
				        "received before the previous one could be handled; the previous one will "
						"be ignored\n";
			}

			state_ = STATE_INT_DELAY;
			intDelay_ = *data;
			cycles_ = SERIAL_DELAY_ALLOWANCE;
			break;

		case STATE_EXT_WAIT_DATA:
		case STATE_EXT_WAIT_DATA_WITH_DELAY:
			// Another internal clock request has been received before the previous one has finished
			// being processed; allow some time for the program to make its next external clock
			// request
			if (state_ == STATE_EXT_WAIT_DATA_WITH_DELAY)
			{
				clog << pt::microsec_clock::local_time() << ": Another internal clock request was "
				        "received before the previous one could be handled; the previous one will "
						"be ignored\n";
			}

			state_ = STATE_EXT_WAIT_DATA_WITH_DELAY;
			intDelay_ = *data;
			break;

		default:
			// The program is not ready to receive data; send back a negative response
			{
				clog << pt::microsec_clock::local_time() << ": An internal clock request was "
				        "received but we are not in a suitable state to handle it (state = "
				     << state_ << ")\n";
				SerialDataMessage response;
				response.sequence = data->sequence;
				response.data = lineState_ ? 0xff : 0x00;

				net_->postMessage(SerialDataMessage::TYPE_INACTIVE,
					basic_string<uint8_t>(reinterpret_cast<uint8_t *>(&response),
					sizeof(response)));
			}
			break;
		}
		break;

	case SerialDataMessage::TYPE_DATA:
	case SerialDataMessage::TYPE_INACTIVE:
		// Save the received value if a transfer is in progress
		if (data->sequence != sequence_)
		{
			// Out of sequence message received
			clog << pt::microsec_clock::local_time()
			     << ": An out of sequence message was received\n";
			break;
		}

		switch (state_)
		{
		case STATE_INT_WAIT_NO_DATA:
			// Save the received data
			state_ = STATE_INT_WAIT_DATA;
			data_ = data->data;
			break;

		case STATE_INT_WAIT_PAUSED:
			// Save the received data and resume emulation
			state_ = STATE_IDLE;
			gb_.cpu_->pause = false;

			gb_.mem_->ioPorts()[SB]  = data->data;
			gb_.mem_->ioPorts()[SC] &= ~0x80;
			gb_.mem_->ioPorts()[IF] |= SERIAL_INTR;

			break;

		default:
			clog << pt::microsec_clock::local_time()
			     << ": An unexpected data message received (state = " << state_ << ")\n";
		}
		break;

	case SYNC_ID:
		// Synchronisation pulse; emulate a frame
		++gb_.frames_;
		break;

	default:
		clog << hex << setfill('0') << pt::microsec_clock::local_time()
		     << ": Unknown message with identifier 0x"
		     << setw(4) << static_cast<unsigned>(identifier) << " received\n";
	}
}

void GbCommsSerial::onBadPacket()
{
	connected_ = false;
	clog << pt::microsec_clock::local_time() << ": A badly formed packet was received\n";
}

void GbCommsSerial::onNetworkError(ErrorType type, const bs::error_code &ec)
{
	connected_ = false;
	switch (type)
	{
	case GBNET_ERR_RESOLVE:
		clog << pt::microsec_clock::local_time()
		     << ": There was an error resolving a network address: ";
		break;

	case GBNET_ERR_ACCEPT:
		clog << pt::microsec_clock::local_time()
		     << ": There was an error accepting client connections: ";
		break;

	case GBNET_ERR_CONNECT:
		clog << pt::microsec_clock::local_time() << ": Failed to connect to the server: ";
		break;

	case GBNET_ERR_RX:
		clog << pt::microsec_clock::local_time()
		     << ": There was an error whilst reading from a socket: ";
		break;

	default:
		clog << pt::microsec_clock::local_time() << ": An unknown networking error occurred: ";
	}
	
	clog << ec.message() << " (" << ec << ")\n";
}