forked from besm6/dubna
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmachine.cpp
420 lines (365 loc) · 12.4 KB
/
machine.cpp
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
//
// BESM-6: Big Electronic Calculating Machine, model 6.
//
// Copyright (c) 2023 Serge Vakulenko
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include "machine.h"
#include <unistd.h>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include "encoding.h"
// Static fields.
bool Machine::verbose = false;
uint64_t Machine::simulated_instructions = 0;
// Limit of instructions, by default.
const uint64_t Machine::DEFAULT_LIMIT = 100ULL * 1000 * 1000 * 1000;
//
// Initialize the machine.
//
Machine::Machine(Memory &m)
: progress_time_last(std::chrono::steady_clock::now()), memory(m), cpu(*this, m)
{
}
//
// Deallocate the machine: disable tracing.
//
Machine::~Machine()
{
redirect_trace(nullptr, "");
enable_trace("");
}
//
// Every few seconds, print a message to stderr, to track the simulation progress.
//
void Machine::show_progress()
{
//
// Check the real time every few thousand cycles.
//
static const uint64_t PROGRESS_INCREMENT = 10000;
if (simulated_instructions >= progress_count + PROGRESS_INCREMENT) {
progress_count += PROGRESS_INCREMENT;
// How much time has passed since the last check?
auto time_now = std::chrono::steady_clock::now();
auto delta = time_now - progress_time_last;
auto sec = std::chrono::duration_cast<std::chrono::seconds>(delta).count();
// Emit message every 5 seconds.
if (sec >= 5) {
std::cerr << "----- Progress " << simulated_instructions << " -----" << std::endl;
progress_time_last = time_now;
}
}
}
//
// Run the machine until completion.
//
void Machine::run()
{
// Show initial state.
trace_registers();
try {
for (;;) {
bool done = cpu.step();
if (progress_message_enabled) {
show_progress();
}
simulated_instructions++;
if (simulated_instructions > instr_limit)
throw std::runtime_error("Simulation limit exceeded");
if (done) {
// Halted by 'стоп' instruction.
cpu.finish();
return;
}
}
} catch (const Processor::Exception &ex) {
// Unexpected situation in the machine.
cpu.stack_correction();
cpu.finish();
auto const *message = ex.what();
if (!message[0]) {
// Empty message - legally halted by extracode e74.
return;
}
std::cerr << "Error: " << message << std::endl;
trace_exception(message);
throw 0;
} catch (std::exception &ex) {
// Something else.
std::cerr << "Error: " << ex.what() << std::endl;
throw 0;
}
}
//
// Fetch instruction word.
//
Word Machine::mem_fetch(unsigned addr)
{
if (addr == 0) {
throw Processor::Exception("Jump to zero");
}
Word val = memory.load(addr);
if (!cpu.on_right_instruction()) {
trace_fetch(addr, val);
}
return val & BITS48;
}
//
// Write word to memory.
//
void Machine::mem_store(unsigned addr, Word val)
{
addr &= BITS(15);
if (addr == 0)
return;
memory.store(addr, val);
trace_memory_write(addr, val);
}
//
// Read word from memory.
//
Word Machine::mem_load(unsigned addr)
{
addr &= BITS(15);
if (addr == 0)
return 0;
Word val = memory.load(addr);
trace_memory_read(addr, val);
return val & BITS48;
}
//
// Load input job from file.
// Throw exception on failure.
//
void Machine::load(const std::string &filename)
{
// Open the input file.
std::ifstream input;
input.open(filename);
if (!input.is_open())
throw std::runtime_error(filename + ": " + std::strerror(errno));
load(input);
}
//
// Load input job from stream to drum #1.
//
void Machine::load(std::istream &input)
{
// Word offset from the beginning of the drum.
unsigned offset = 0;
while (input.good()) {
if (offset >= 040 * PAGE_NWORDS)
throw std::runtime_error("Input job is too large");
// Get next line.
std::string line;
getline(input, line);
// Write to drum in COSY format.
drum_write_cosy(1, offset, line);
}
}
//
// Encode line as COSY and write to drum.
// Update offset.
//
void Machine::drum_write_cosy(unsigned drum_unit, unsigned &offset, const std::string &input)
{
// Convert input from UTF-8 to KOI-7.
// Encode as COSY.
std::string line = encode_cosy(utf8_to_koi7(input));
// Write to drum as words.
for (; line.size() >= 6; line.erase(0, 6)) {
Word word = (uint8_t)line[0];
word = word << 8 | (uint8_t)line[1];
word = word << 8 | (uint8_t)line[2];
word = word << 8 | (uint8_t)line[3];
word = word << 8 | (uint8_t)line[4];
word = word << 8 | (uint8_t)line[5];
drum_write_word(drum_unit, offset++, word);
}
}
//
// Disk read/write.
//
void Machine::disk_io(char op, unsigned disk_unit, unsigned zone, unsigned sector, unsigned addr,
unsigned nwords)
{
if (disk_unit >= NDRUMS)
throw std::runtime_error("Invalid disk unit " + to_octal(disk_unit));
if (!disks[disk_unit]) {
// Disk must be previously configured using disk_mount().
throw std::runtime_error("Disk unit " + to_octal(disk_unit + 030) + " is not mounted");
}
if (op == 'r') {
disks[disk_unit]->disk_to_memory(zone, sector, addr, nwords);
// Debug: dump the data.
if (dump_io_flag) {
memory.dump(++dump_serial_num, disk_unit + 030, zone, sector, addr, nwords);
}
} else {
disks[disk_unit]->memory_to_disk(zone, sector, addr, nwords);
}
}
//
// Drum read/write.
//
void Machine::drum_io(char op, unsigned drum_unit, unsigned zone, unsigned sector, unsigned addr,
unsigned nwords)
{
drum_init(drum_unit);
if (op == 'r') {
drums[drum_unit]->drum_to_memory(zone, sector, addr, nwords);
} else {
drums[drum_unit]->memory_to_drum(zone, sector, addr, nwords);
}
}
//
// Write one word to drum.
//
void Machine::drum_write_word(unsigned drum_unit, unsigned offset, Word value)
{
drum_init(drum_unit);
drums[drum_unit]->write_word(offset, value);
}
//
// Read one word from drum.
//
Word Machine::drum_read_word(unsigned drum_unit, unsigned offset)
{
drum_init(drum_unit);
return drums[drum_unit]->read_word(offset);
}
//
// Allocate drum on first access.
//
void Machine::drum_init(unsigned drum_unit)
{
if (drum_unit >= NDRUMS)
throw std::runtime_error("Invalid drum unit " + to_octal(drum_unit));
if (!drums[drum_unit]) {
// Allocate new drum on first request.
drums[drum_unit] = std::make_unique<Drum>(memory);
}
}
//
// Open binary image and assign it to the disk unit.
//
void Machine::disk_mount(unsigned disk_unit, const std::string &filename, bool write_permit)
{
if (disk_unit < 030 || disk_unit >= 070)
throw std::runtime_error("Invalid disk unit " + to_octal(disk_unit) + " in disk_mount()");
disk_unit -= 030;
if (disks[disk_unit])
throw std::runtime_error("Disk unit " + to_octal(disk_unit + 030) + " is already mounted");
// Open binary image as disk.
auto path = disk_find(filename);
disks[disk_unit] = std::make_unique<Disk>(memory, path, write_permit);
std::cout << "Mount image '" << path << "' as disk " << to_octal(disk_unit + 030) << std::endl;
}
//
// Redirect drum to disk.
// It's called Phys.IO in Dispak.
//
void Machine::map_drum_to_disk(unsigned drum, unsigned disk)
{
mapped_drum = drum;
mapped_disk = disk;
std::cout << "Redirect drum " << to_octal(mapped_drum) << " to disk " << to_octal(mapped_disk)
<< std::endl;
}
//
// Find file at pre-defined places.
// 1. Use envorinment variable BESM6_PATH.
// 2. Try ~/.besm6 directory.
// 3. Try /usr/local/share/besm6 directory.
//
std::string Machine::disk_find(const std::string &filename)
{
if (filename.find('/') != std::string::npos) {
// Slash is present in file name, so we assume it's absolute.
return filename;
}
// Setup the list of directories to search.
if (disk_search_path.empty()) {
auto env_besm6_path = std::getenv("BESM6_PATH");
if (env_besm6_path != nullptr) {
disk_search_path = env_besm6_path;
} else {
// No BESM6_PATH, so use the default.
auto env_home = std::getenv("HOME");
if (env_home != nullptr) {
disk_search_path = env_home;
}
disk_search_path += "/.besm6:/usr/local/share/besm6";
}
}
// Iterate the search path using string stream.
std::stringstream list(disk_search_path);
while (list.good()) {
// Get directory name from the list.
std::string name;
getline(list, name, ':');
// Check for disk image here.
name += "/";
name += filename;
if (access(name.c_str(), R_OK) >= 0) {
return name;
}
}
throw std::runtime_error("Cannot find file '" + filename + "'");
}
//
// Load boot code for Monitoring System Dubna.
//
void Machine::boot_ms_dubna()
{
//
// I got this magic code from Mikhail Popov.
// See https://groups.google.com/g/besm6/c/e5jM_R1Oozc/m/aGfCePzsCwAJ
// It more or less coincides with sources of STARTJOB routine
// at https://github.com/besm6/besm6.github.io/blob/master/sources/dubna/cross/extold.txt#L250
//
// clang-format off
memory.store(02010, besm6_asm("vtm -5(1), *70 3002")); // читаем инициатор монитора
memory.store(02011, besm6_asm("xta 377, atx 3010")); // берем тракт, где MONITOR* + /MONTRAN
memory.store(02012, besm6_asm("xta 363, atx 100")); // ТРП для загрузчика
memory.store(02013, besm6_asm("vtm 53401(17), utc")); // магазин
memory.store(02014, besm6_asm("*70 3010(1), utc")); // каталоги
memory.store(02015, besm6_asm("vlm 2014(1), ita 17")); // aload по адресу 716b
memory.store(02016, besm6_asm("atx 716, *70 717")); // infloa по адресу 717b - статический загрузчик
memory.store(02017, besm6_asm("xta 17, ati 16")); //
memory.store(02020, besm6_asm("atx 2(16), arx 3001")); // прибавляем 10b
memory.store(02021, besm6_asm("atx 17, xta 3000")); // 'INPUTCAL'
memory.store(02022, besm6_asm("atx (16), vtm 1673(15)")); // call CHEKJOB*
memory.store(02023, besm6_asm("uj (17), utc")); // в статический загрузчик
memory.store(03000, 0'5156'6065'6443'4154ul); // 'INPUTCAL' in Text encoding
memory.store(03001, 0'0000'0000'0000'0010ul); // прибавляем 10b
memory.store(03002, 0'4014'0000'0021'0201ul); // инициатор
memory.store(03003, 0'0000'0000'0020'0000ul); // таблица резидентных программ
memory.store(03004, 0'0014'0000'0021'0007ul); // каталоги
memory.store(03005, 0'0000'0000'0021'0000ul); // временной
memory.store(03006, 0'0014'0000'0021'0010ul); // библиотеки
memory.store(03007, 0'0000'0000'0021'0001ul); // (физ. и мат.)
memory.store(03010, 0'0014'0000'0021'0035ul); // /MONTRAN
// clang-format on
cpu.set_pc(02010);
}