aboutsummaryrefslogtreecommitdiff
path: root/comhan.c
blob: 0f5812f5e412d9ec7b49d3dc818787fb7a3c040b (plain)
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/*
 *   file:  comhan.c
 *
 *   This file is the command handler for the
 *   MPX operating system.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "mpx.h"

#define BUF_SIZE 80      /* Size of the command line buffer. */

#define VERSION        0
#define DATE           1
#define DIRECTORY      2
#define STOP           3
#define HELP           4
#define PROMPT         5
#define ALIAS          6
#define SHOW           7
#define ALLOCATE       8
#define CMD_FREE       9
#define CMD_LOAD      10
#define CMD_RESUME    11
#define CMD_RUN       12
#define CMD_SUSPEND   13
#define CMD_TERMINATE 14
#define CMD_SETPRI    15
#define CMD_DISPATCH  16
#define CLOCK     17

#define NUM_CMDS 18

int length;             /* Length of the command line.      */
unsigned sp_save;       /* A stack save for mod 4 dispatch. */

char prompt[20] = "mpx>";
const char version[] = "MPX OS - Version 1.0\n";
char date[] = "01/09/1991";

char *cmds[] = { "version", "date", "directory", "stop",
				 "help", "prompt", "alias", "show",
				 "allocate", "free", "load", "resume",
				 "run", "suspend", "terminate", "setpriority",
				 "dispatch", "clock", NULL};
char *aliases[] = {"        ", "        ", "        ", "        ",
				   "        ", "        ", "        ", "        ",
				   "        ", "        ", "        ", "        ",
				   "        ", "        ", "        ", "        ",
				   "        ", "        ", NULL};

/*
 *   comhan()    This is the command handler for the MPX OS.
 *               It repeatedly prints a prompt, makes a system
 *               request to read from the console, and then
 *               carries out the command.
 *
 *   Parameters: None.
 *   Return value: None.
 */

void comhan() {
	static char *args[7]; //one more than expected number of arguments
	static char buffer[BUF_SIZE];
	int do_stop = 0;

	do {
	  printf("%s ",prompt);              /* Print a prompt.         */
	  length = BUF_SIZE;                 /* Reset length of buffer. */
	  sys_req(CON,READ,buffer,&length);  /* Request CON input       */

	  set_args(buffer, args);

	  switch (get_cmd(args[0])) {
		case VERSION:   cmd_version();        break;
		case DATE:          cmd_date(args);       break;
		case DIRECTORY:     cmd_directory();      break;
		case STOP:          do_stop = cmd_stop(); break;
		case HELP:          cmd_help(args);       break;
		case PROMPT:        cmd_prompt(args);     break;
		case ALIAS:         cmd_alias(args);      break;
		case SHOW:          cmd_show(args);       break;
		case ALLOCATE:      cmd_allocate(args);   break;
		case CMD_FREE:      cmd_free(args);       break;
		case CMD_LOAD:      cmd_load(args);       break;
		case CMD_RESUME:    cmd_resume(args);     break;
		case CMD_RUN:       cmd_run(args);        break;
		case CMD_SUSPEND:   cmd_suspend(args);    break;
		case CMD_TERMINATE: cmd_terminate(args);  break;
		case CMD_SETPRI:    cmd_setpri(args);     break;
		case CMD_DISPATCH:  cmd_dispatch();       break;
		case CLOCK:     cmd_clock(args);      break;
		default:
		  printf("Can't recognize.\n");
		  break;
	  }
	} while (!do_stop);
}

int get_cmd(char cmd[]){
  /* return the number associated with a command (use STOP, HELP etc) */

  int i = 0; //loop control

  if (cmd == NULL) {
	return -1;
  }

  strlwr(cmd);

  while (cmds[i] != NULL) {
	if (strcmp(cmds[i], cmd)==0 || strcmp(aliases[i], cmd)==0){
	  return i;
	}
	i++;
  }

  //default - means it wasn't a valid command
  return -1;
}

int set_args(char buffer[], char *args[]) {
  /* use string tok to set the contents of args from buffer
	 and return the number of args (will go into argc) */
  char separators[5] = " =/,:"; //Characters that separate tokens
  int i = 0; //loop control

  args[i] = strtok(buffer, separators); //Get first token
  while(args[i] != NULL){
	args[++i] = strtok(NULL, separators); //Get next tokens
  }

  return i;
}
/**
 * Print the version number.
 */
void cmd_version() {
  printf("%s", version);
}

/**
 * Print or change the date
 */
void cmd_date(char *args[]){

  int m, d, y;

  if (strcmp("", args[1])==0) {
	printf("%s \n", date);
  } else {

	m = atoi(args[1]);
	d = atoi(args[2]);
	y = atoi(args[3]);

	if (m > 0 && m < 13 && d > 0 && d < 32) {
	  sprintf(date, "%d/%d/%d", m, d, y);
	} else {
	  printf("Invalid date. \n");
	}
  }
}
void cmd_directory(){
  int no_proc = directory(direct, DIR_SIZE);
  int i;

  if (no_proc == 1) {
	printf("You have 1 program \n");
  } else if (no_proc == 0) {
	printf("You have no programs \n");
  } else {
	printf("You have %d programs \n", no_proc);
  }

  if (no_proc > 0) {
	printf("Size      Name \n");
	printf("========= =========================== \n");
  }

  for (i = 0; i < no_proc; i++) {
	printf("%8d  %s \n", direct[i].dirsiz, direct[i].dirnam);
  }
}

/**
 * Print a goodbye message
 */
int cmd_stop(){
  char buffer[2];
  int length = 2;
  pcb *p = pcb_list;

  printf("Are you sure you want to exit? [y/n]: ");
  sys_req(CON,READ,buffer,&length);

  if (strcmp(buffer, "y") == 0 || strcmp(buffer, "Y") == 0) {
	do {
	  if(p->type != FREE) {
		freemem(p->loadaddr);
		free_pcb(pcb_list, p);
	  }
	  p = p->chain;
	} while(p != NULL);
	printf("** COMHAN execution complete **\n");
	return 1;
  } else {
	return 0;
  }
}

/**
 * Print information about the COMHAN commands.
 * Will print all commands or just information specific to the
 * argument if given.
 */
void cmd_help(char *args[]) {
  int i;
  char *help[NUM_CMDS];

  help[VERSION]       = "version              Display version number";
  help[HELP]          = "help                 Provide information about commands";
  help[DIRECTORY]     = "directory            List .mpx files";
  help[DATE]          = "date [mm/dd/yyyy]    Display or set the system date";
  help[STOP]          = "stop                 Terminate execution of COMHAN";
  help[PROMPT]        = "prompt string        Change the prompt for commands";
  help[ALIAS]         = "alias command=string Create an alias for a command";
  help[SHOW]          = "show                 Prints PCB information";
  help[ALLOCATE]      = "allocate             Builds PCB with specified options";
  help[CMD_FREE]      = "free name            Frees the PCB called name";
  help[CMD_LOAD]      = "load name[=ppp]      Creates a process called name with priority ppp";
  help[CMD_RESUME]    = "resume name          Resumes the process called name";
  help[CMD_RUN]       = "run name[=ppp]       Runs a process called name with priority ppp";
  help[CMD_SUSPEND]   = "suspend name         Suspends the process called name";
  help[CMD_TERMINATE] = "terminate name       Terminates the process called name";
  help[CMD_SETPRI]    = "setpriority name=ppp Sets the priority of process name";
  help[CMD_DISPATCH]  = "dispatch             Runs each process once";
  help[CLOCK]         = "clock [stop|start]   Perform clock operations";

  // print header
  printf(               "  Name                 Use \n");
  printf(               "  ==================== ================================================= \n");

  if (args[1] != NULL) {
	// print help for specific command
	printf("  %s \n", help[ get_cmd(args[1]) ] );
  } else {
	// list all help
	for (i = 0; i < NUM_CMDS; i++) {
	  printf("  %s \n", help[i]);
	}
  }
}

/**
 * Change the prompt.
 */
void cmd_prompt(char *args[]){
  strcpy(prompt, args[1]);
}

void cmd_alias(char *args[]){
  //get the number of the command to alias
  int num = get_cmd(args[1]);
  strcpy(aliases[num], args[2]);
  num ++;
}

void print_pcb(pcb * p) {

	char str[4];

	if (p->type == FREE) {
		str[0] = 'f';
	} else if (p->type == SYS_PROCESS) {
		str[0] = 's';
	} else if (p->type == APP_PROCESS) {
		str[0] = 'a';
	} else {
		str[0] = '-';
	}

	if (p->state == READY) {
		str[1] = 'r';
	} else if (p->state == RUNNING) {
		str[1] = 'o';
	} else if (p->state == BLOCKED) {
		str[1] = 'b';
	} else {
		str[1] = '-';
	}

	if (p->suspend == SUSPENDED) {
		str[2] = 'y';
	} else if (p->suspend == NOT_SUSPENDED) {
		str[2] = 'n';
	} else {
		str[2] = '-';
	}

	str[3] = '\0';

	printf("0x%04x %8s %s 0x%04x 0x%04x 0x%04x %3d 0x%04x \n",
		  p, p->name, str, p->chain, p->prev,
		  p->next, p->priority, p->loadaddr);
}

void cmd_show(char *args[]) {
  pcb * current = pcb_list;

  if (!args[1]) {
	printf("Show: free, all, system, application, \n");
	printf("      suspended, ready, init. \n");
	return;
  }

  printf("PCB_Ad Name     TSP chain  prev   next   pri l_addr \n");
  printf("------ -------- --- ------ ------ ------ --- ------ \n");

  if (strcmp(args[1], "init") == 0 || strcmp(args[1], "ready") == 0) {
	current = (strcmp(args[1], "init") == 0)? io_init_queue : ready_queue;

	if (current == NULL) {
	  return;
	}

	do {
	  print_pcb(current);
	  current = current->next;
	} while (current != NULL);
	return;
  }

  do {
	if (strcmp(args[1], "free") == 0 && current->type == FREE) {
		print_pcb(current);
	} else if (strcmp(args[1], "all") == 0) {
		print_pcb(current);
	} else if (strcmp(args[1], "system") == 0 &&
	  current->type == SYS_PROCESS) {
		print_pcb(current);
	} else if (strcmp(args[1], "application") == 0 &&
	  current->type == APP_PROCESS) {
		print_pcb(current);
	} else if (strcmp(args[1], "suspended") == 0 &&
	  current->suspend == SUSPENDED) {
		print_pcb(current);
	} else if (strcmp(args[1], "ready") == 0 &&
	  current->state == READY) {
		print_pcb(current);
	}

	current = current->chain;
  } while (current != NULL);
}

void cmd_allocate(char *args[]) {
  pcb * new;
  int result;
  int type, state, suspend, priority;
  pcb * exists;

  if (!args[1] || !args[2] || !args[3] || !args[4] || !args[5]) {
	printf("Error: Please use the correct number of arguments. \n");
	return;
  }

  if (strcmp(args[2], "f") != 0 &&
	  strcmp(args[2], "a") != 0 &&
	  strcmp(args[2], "s") != 0) {
		printf("Error: PCB type must be f(ree), a(pplication) or s(ystem). \n");
		printf("You said: %s \n", args[2]);
		return;
  }

  if (strcmp(args[3], "r") != 0 &&
	  strcmp(args[3], "o") != 0 &&
	  strcmp(args[3], "b") != 0) {
		printf("Error: PCB state must be r(eady), o(running), or b(locked). \n");
		printf("You said: %s \n", args[3]);
		return;
  }

  if (strcmp(args[4], "y") != 0 &&
	  strcmp(args[4], "n") != 0) {
		printf("Error: PCB suspended flag must be y(es) or n(o). \n");
		printf("You said: %s \n", args[4]);
		return;
  }

  priority = atoi(args[5]);

  exists = search_pcb(pcb_list, args[1]);

  if(exists != NULL){
	printf("Error: A pcb with that name already esists. \n");
	return;
  }

  new = get_pcb(pcb_list);

  type = FREE;
  if (strcmp(args[2], "a") == 0) {
	type = APP_PROCESS;
  } else if (strcmp(args[2], "s") == 0) {
	type = SYS_PROCESS;
  }

  state = READY;
  if (strcmp(args[3], "o") == 0) {
	state = RUNNING;
  } else if (strcmp(args[3], "b") == 0) {
	state = BLOCKED;
  }

  suspend = NOT_SUSPENDED;
  if (strcmp(args[4], "y") == 0) {
	suspend = SUSPENDED;
  }

  if (type == APP_PROCESS && (priority < -126 || priority > 126)) {
	printf("Error: The priority for an application process must be \n");
	printf("between -126 and 126, inclusive. \n");
	return;
  }

  if (type == SYS_PROCESS && (priority < -128 || priority > 127)) {
	printf("Error: The priority for a system process must be \n");
	printf("between -128 and 127, inclusive. \n");
	return;
  }

  result = build_pcb(new, args[1], type, state, suspend, priority,
					 NULL, NULL, NULL, NULL);

  switch (result) {
	case 1:  break;

	case -1: printf("Error: There was no space for another pcb. \n");
			 break;

	case -2: printf("Error: Invalid type \n");
			 break;

	case -3: printf("Error: Invalid state \n");
			 break;

	case -4: printf("Error: Invalid suspend \n");
			 break;
  }

  //put the pcb in a queue
  if (state == READY) {
	insert_pcb(&ready_queue, new, 0); //insert in priority order
  } else if (state == BLOCKED) {
	insert_pcb(&io_init_queue, new, 1); //insert at end of queue
  }

  return;
}

void cmd_free(char *args[]) {
  pcb * to_free = search_pcb(pcb_list, args[1]);
  int result;

  if (to_free->state == READY) {
	remove_pcb(&ready_queue, to_free);
  } else if(to_free->state == BLOCKED) {
	remove_pcb(&io_init_queue, to_free);
  }

  result = free_pcb(pcb_list, to_free);
  switch (result) {
	case -1: printf("Error: Couldn't find PCB\n"); break;
	case -2: printf("Error: PCB already free\n");  break;
  }
}

/**
 * Load
 */
void cmd_load(char *args[]) {
  int i, ret, priority = 0;
  unsigned segp;
  pcb *p;
  int paragraphs;
  char* name = args[1];
  // figure out how many directory entries
  int num = directory(direct, DIR_SIZE);

  // search in the directory for the specified program
  i = 0;
  while (stricmp(direct[i].dirnam, name) != 0) {
	i++;
	if (i == num) {
	  // no program found
	  printf("Error: No program found with that name. \n");
	  return;
	}
  }

  // figure out how much memory we need
  paragraphs = (unsigned) ceil(direct[i].dirsiz / 16);

  // try to allocate the needed memory
  if (allocmem(paragraphs, &segp) != -1) {
	// insufficient memory
	printf("Error: Insufficient memory. \n");
	return;
  }

  // read the file into memory
  if (load((unsigned *)segp, direct[i].dirnam) != 0) {
	// load error
	printf("Error: Could not load program into memory. \n");
	return;
  }

  // if a valid priority was specified, replace the default
  if (args[2] != NULL) {
	if (atoi(args[2]) >= -126 && atoi(args[2]) <= 126) {
	  priority = atoi(args[2]);
	} else {
	  printf("Warning: invalid priority specified, using default. \n");
	}
  }

  // now we can put the proc into a PCB
  p = get_pcb(pcb_list);

  if (p == NULL) {
	printf("Error: No free PCBs. \n");
	return;
  }

  if (build_pcb(p, args[1], APP_PROCESS, READY, SUSPENDED,
	priority, segp, 0 /* ip */, 0 /* ds */, 0x200) != 1) {
	printf("Error: Unable to build PCB. \n");
	return;
  }

  insert_pcb(&ready_queue, p, 0);
  return;
}

/**
 * Resume
 */
void cmd_resume(char *args[]) {

  pcb *p = pcb_list;

  if (args[1] != NULL) {
	if (strcmp(args[1], "*") == 0) {
	  // resume all processes
	  // set suspended to NOT_SUSPENDED for all application PCBs
	  do {
		if (p->type == APP_PROCESS) {
		  p->suspend = NOT_SUSPENDED;
		}
		p = p->chain;
	  } while (p != NULL);
	} else {
	  // search for the correct PCB and set suspended to NOT_SUSPENDED
	  p = search_pcb(pcb_list, args[1]);
	  if (p != NULL) {
		p->suspend = NOT_SUSPENDED;
	  } else {
		printf("No process named %s. \n", args[1]);
	  }
	}
  } else {
	printf("No process specified. Please run resume proc \n");
	printf("for process proc. To resume all processes, \n");
	printf("type resume * \n");
  }
}

/**
 * Run
 */
void cmd_run(char *args[]) {
  pcb *p;
  // load the process ...
  cmd_load(args);

  // ... then set it to be not suspended
  p = search_pcb(pcb_list, args[1]);
  if (p != NULL){
	p->suspend = NOT_SUSPENDED;
  } else {
	printf("Error: process did not load correctly. \n");
  }
}

/**
 * Suspend
 */
void cmd_suspend(char *args[]) {
  pcb *p;

  // Get the pcb...
  p = search_pcb(pcb_list, args[1]);

  if (p != NULL) {
	// ... and suspend it
	p->suspend = SUSPENDED;
  } else {
	printf("No process with the specified name. \n");
  }
}

/**
 * Terminate
 */
void cmd_terminate(char *args[]) {
   pcb *p;

   // the "terminate *" case
   if (strcmp(args[1], "*") == 0) {
	 p = pcb_list;
	 do {
	   if (p->type == APP_PROCESS) {
		 // remove from queue as needed
		 if (p->state == READY) {
		   remove_pcb(&ready_queue, p);
		 } else if (p->state == BLOCKED) {
		   remove_pcb(&io_init_queue, p);
		 }

		 // free it
		 freemem(p->loadaddr);
		 free_pcb(pcb_list, p);
	   }
	   p = p -> chain;
	 } while (p != NULL);
   } else {
	 // the "terminate proc" case
	 p = search_pcb(pcb_list, args[1]);

	 if (p != NULL && p->type == APP_PROCESS) {

	   // remove from queue as needed
	   if (p->state == READY) {
		 remove_pcb(&ready_queue, p);
	   } else if (p->state == BLOCKED) {
		 remove_pcb(&io_init_queue, p);
	   }

	   // free it
	   freemem(p->loadaddr);
	   free_pcb(pcb_list, p);
	 } else {
	   printf("No process with the specified name. \n");
	 }
   }
   return;
}

/**
 * Set Priority
 */
void cmd_setpri(char *args[]) {
  pcb *p;
  int new_priority;

  // Get the pcb
  p = search_pcb(pcb_list, args[1]);
  new_priority = atoi(args[2]);

  if (p != NULL) {
	// Check the priority is valid
	if (p->type == APP_PROCESS && new_priority >= -128 && new_priority <= 127) {
	  remove_pcb(&ready_queue, p);      // Take pcb out of ready queue
	  p->priority = new_priority;       // Change priority
	  insert_pcb(&ready_queue, p, 0);   // Re-insert pcb in ready queue
	} else {
	  printf("Error: invalid priority. \n");
	}
  } else {
	printf("Error: invalid process name. \n");
  }
}

/**
 * Dispatch
 */
void cmd_dispatch() {
  // set up a pointer to the ready queue
  pcb dummy;
  cop = &dummy;
  cop -> next = ready_queue;

  // save the stack pointer so we can return here
  sp_save = _SP - 24;

  // call sys_sppt's dispatch
  dispatch();
  return;
}

/*
 * stop, start, set, or show the clock based on args[1]
 */
void cmd_clock(char *args[]){
  int hr, m, s;
  int ret;
  // decide what clock operation to perform
  if (strcmp(args[1], "stop") == 0) {
	stop_clock();
	return;
  } else if (strcmp(args[1], "start") == 0) {
	start_clock();
	return;
  } else if (strcmp(args[1], "") == 0) {
	read_clock(&hr, &m, &s);
	printf("The current time is %d:%d:%d\n", hr, m, s);
	return;
  } else {
	// the remaining case is to set the clock
	// parse the input - should be "hh:mm:ss"
	ret = set_clock(atoi(args[1]), atoi(args[2]), atoi(args[3]));
	// call sys_sppt's set_clock(hr, mn, s)
	// if set_clock returns -1 print error message
	if (ret == -1) {
	  printf("Error setting clock\n");
	}
  }
}