-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsys.c
More file actions
718 lines (560 loc) · 14.4 KB
/
sys.c
File metadata and controls
718 lines (560 loc) · 14.4 KB
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
/*
* sys.c - Syscalls implementation
*/
#include <devices.h>
#include <utils.h>
#include <io.h>
#include <mm.h>
#include <mm_address.h>
#include <sched.h>
#include <errno.h>
#include <circ_buff.h>
#include <sem.h>
#define LECTURA 0
#define ESCRIPTURA 1
extern unsigned long zeos_ticks;
extern unsigned long quantum_ticks;
extern struct list_head freequeue, readyqueue;
extern struct circ_buff cb;
extern struct list_head keyboardqueue;
extern Byte x, y;
extern Byte color;
unsigned int next_pid = 2;
sem_t semaforos[MAX_SEMAFOROS];
int ret_from_fork()
{
ready_to_system();
return 0;
}
int check_fd(int fd, int permissions)
{
if (fd!=1) return -9; /*EBADF*/
if (permissions!=ESCRIPTURA) return -13; /*EACCES*/
return 0;
}
int sys_ni_syscall()
{
return -38; /*ENOSYS*/
}
int sys_getpid()
{
return current()->PID;
}
int sys_fork()
{
int PID = -1;
if(list_empty(&freequeue))
{
return -1;
}
// Pillamos el task_struct si quedan disponibles
struct list_head *first = list_first(&freequeue);
struct task_struct *new_struct = list_head_to_task_struct(first);
list_del(first);
union task_union *new_union = (union task_union *) new_struct;
// Pillamos el padre
struct task_struct *current_struct = current();
union task_union *current_union = (union task_union *)current_struct;
// copia de los datos de la pila de sistema
copy_data(current_union, new_union, KERNEL_STACK_SIZE*4);
// asignar espacio de directorio
allocate_DIR(new_struct);
page_table_entry *new_page_table = get_PT(new_struct);
int new_frame;
for (int i = 0; i < NUM_PAG_DATA; ++i)
{
new_frame = alloc_frame();
if (new_frame != -1)
{
set_ss_pag(new_page_table, PAG_LOG_INIT_DATA + i, new_frame);
}
else // dealocatar todo
{
// hacemos el bucle hacia atrás
for (; i >= 0; --i)
{
free_frame(get_frame(new_page_table, PAG_LOG_INIT_DATA + i));
del_ss_pag(new_page_table, PAG_LOG_INIT_DATA + i);
}
list_add_tail(first, &freequeue);
return -ENOMEM;
}
}
page_table_entry *current_page_table = get_PT(current_struct);
for (int i = 0; i < NUM_PAG_KERNEL; ++i)
{
set_ss_pag(new_page_table, i, get_frame(current_page_table, i));
}
for (int i = 0; i < NUM_PAG_CODE; ++i)
{
set_ss_pag(new_page_table, PAG_LOG_INIT_CODE + i,
get_frame(current_page_table, PAG_LOG_INIT_CODE + i));
}
for (int i = 0; i < NUM_PAG_DATA; ++i)
{
set_ss_pag(current_page_table, TOTAL_PAGES - NUM_PAG_DATA + i,
get_frame(new_page_table, PAG_LOG_INIT_DATA + i));
copy_data((void *)((PAG_LOG_INIT_DATA + i) << 12),
(void *)((TOTAL_PAGES - NUM_PAG_DATA + i) << 12), PAGE_SIZE);
del_ss_pag(current_page_table, TOTAL_PAGES - NUM_PAG_DATA + i);
}
//Flush TLB
set_cr3(get_DIR(current()));
new_union->stack[KERNEL_STACK_SIZE - 0x13] = 0;
new_union->stack[KERNEL_STACK_SIZE - 0x12] = (unsigned long) &ret_from_fork;
new_struct->kernel_esp = (unsigned long)&new_union->stack[KERNEL_STACK_SIZE - 0x13];
// crear el proceso hijo
PID=next_pid++;
new_struct->PID= PID;
new_struct->state = ST_READY;
new_struct->threads_qtt = 1;
initialize_stats(new_struct);
list_add_tail(&(new_struct->list), &readyqueue);
return PID;
}
void sys_exit()
{
struct task_struct *proc = current();
proc->threads_qtt--;
// eliminar la memoria allocada para datos
page_table_entry *exit_proc_page_table = get_PT(proc);
if (proc->threads_qtt == 0)
{
for (int i = 0; i < NUM_PAG_DATA; ++i)
{
free_frame(get_frame(exit_proc_page_table, PAG_LOG_INIT_DATA + i));
del_ss_pag(exit_proc_page_table, PAG_LOG_INIT_DATA + i);
}
}
else {
for (int i = 0; i < proc->stack_size; ++i)
{
free_frame(get_frame(exit_proc_page_table, proc->base_stack + i));
del_ss_pag(exit_proc_page_table, proc->base_stack + i);
}
}
// liberar estructuras de datos del proceso
proc->dir_pages_baseAddr = NULL;
proc->PID = -1;
// uso del scheduler para cambiar de proceso
update_process_state_rr(proc, &freequeue);
sched_next_rr();
}
#define BUFFER_SIZE 256
char buff[BUFFER_SIZE];
int sys_write(int fd, char *buffer, int size)
{
int fd_e = check_fd(fd, ESCRIPTURA);
if (fd_e)
{
return fd_e;
}
if (buffer == NULL)
{
return -EFAULT;
}
if (size < 0)
{
return -EINVAL;
}
int written = 0;
int size_written = 0;
while (size > BUFFER_SIZE)
{
copy_from_user(buffer, buff, BUFFER_SIZE);
size_written += sys_write_console(buff, BUFFER_SIZE);
size -= size_written;
written += size_written;
}
if (size)
{
copy_from_user(buffer, buff, size);
written += sys_write_console(buff, size);
}
return written;
}
int sys_gettime(){
return zeos_ticks;
}
int sys_get_stats(int pid, struct stats *st)
{
if (pid < 0)
{
return -EINVAL;
}
for (int i = 0; i < NR_TASKS; ++i)
{
if (task[i].task.PID == pid)
{
task[i].task.stats.remaining_ticks = quantum_ticks;
copy_to_user(&task[i].task.stats, st, sizeof(struct stats));
return 0;
}
}
return -ESRCH;
}
int sys_waitKey(char *b, int timeout)
{
// comprobar que hay elementos en el buffer circular de teclado
if (!cb_empty(&cb))
{
*b = cb_next(&cb);
return 0;
}
// no hay elementos en el buffer circular de teclado
// -------------------------------------------------
// si el timeout es 0, devolver error
if (timeout == 0)
{
return -EAGAIN;
}
// si el timeout es -1, bloquear indefinidadmente hasta que haya un elemento en el buffer circular de teclado
if (timeout < 0)
{
// bloquear el proceso
update_process_state_rr(current(), &keyboardqueue);
sched_next_rr();
// cuando se desbloquee, devolver el elemento del buffer circular de teclado
*b = cb_next(&cb);
return 0;
}
// si el timeout es mayor que 0, bloquear hasta que haya un elemento en el buffer circular de teclado o hasta que se cumpla el timeout
// bloquear el proceso
current()->timeout = timeout;
update_process_state_rr(current(), &keyboardqueue);
sched_next_rr();
// al desbloquear se comprueba si hay elementos en el buffer circular de teclado
if (!cb_empty(&cb))
{
// si hay elementos, devolver el elemento del buffer circular de teclado
*b = cb_next(&cb);
return 0;
}
else
{
// si no hay elementos, devolver error
return -EAGAIN;
}
}
int sys_goto_xy(int goto_x, int goto_y)
{
if (goto_x < 0 || goto_x >= NUM_COLUMNS || goto_y < 0 || goto_y >= NUM_ROWS)
{
return -EINVAL;
}
x = goto_x;
y = goto_y;
return 0;
}
int sys_change_color(int fg, int bg)
{
if (fg < 0 || fg > 15 || bg < 0 || bg > 7)
{
return -EINVAL;
}
color = 0 | bg << 4 | fg;
return 0;
}
int sys_clrscr(char *b)
{
Word *screen = (Word *)0xb8000;
if (b == NULL)
{
for (int i = 0; i < NUM_COLUMNS; ++i)
{
for (int j = 0; j < NUM_ROWS; ++j)
{
screen[(j * NUM_COLUMNS + i)] = 0;
}
}
}
else
{
for (int i = 0; i < NUM_COLUMNS; i++)
{
for (int j = 0; j < NUM_ROWS; ++j)
{
screen[j * NUM_COLUMNS + i] = (b[(j * NUM_COLUMNS + i)*2 + 1] << 8) |
b[(j * NUM_COLUMNS + i)*2];
}
}
}
return 0;
}
int sys_thread_create_with_stack(void (*function)(void *arg), int N, void* parameter)
{
if (N <= 0) // Tiene que tener stack
{
return -EINVAL;
}
// comprobar que quedan tasks libres
if (list_empty(&freequeue))
{
return -ENOMEM;
}
current()->threads_qtt++;
// Pillamos el task_struct si quedan disponibles
struct list_head *first = list_first(&freequeue);
struct task_struct *new_struct = list_head_to_task_struct(first);
list_del(first);
union task_union *new_union = (union task_union *) new_struct;
// copia de los datos de la pila de sistema
copy_data((union task_union *)current(), new_union, KERNEL_STACK_SIZE*4);
new_struct->PID = current()->PID; // usamos el mismo PID que el proceso padre
// usamos el mismo directorio que el proceso padre
new_struct->dir_pages_baseAddr = current()->dir_pages_baseAddr;
// copia de las tablas de páginas
page_table_entry *pag_table = get_PT(new_struct);
page_table_entry *parent_pag_table = get_PT(current());
// copia de todas las páginas de la tabla padre a la hija a la vez que se busca N páginas
// consecutivas disponibles
int num_consecutives = 0;
int first_consecutive = -1;
int new_frame;
int found = 0;
for (int i = 0; i < TOTAL_PAGES; ++i)
{
if (!found)
{
if (pag_table[i].bits.present == 0)
{
if (num_consecutives == 0)
{
first_consecutive = i;
}
if (++num_consecutives == N)
{
found = 1;
}
}
else
{
num_consecutives = 0;
}
}
}
if (!found) // mo hay páginas disponibles para el stack
{
list_add_tail(first, &freequeue);
return -ENOMEM;
}
// allocatar las N páginas consecutivas
for (int i = 0; i < N; ++i)
{
new_frame = alloc_frame();
if (new_frame != -1)
{
set_ss_pag(pag_table, first_consecutive + i, new_frame);
}
else // dealocatar todo si no queda memoria física
{
// hacemos el bucle hacia atrás
for (; i >= 0; --i)
{
free_frame(get_frame(pag_table, first_consecutive + i));
del_ss_pag(pag_table, first_consecutive + i);
}
list_add_tail(first, &freequeue);
return -ENOMEM;
}
}
// configuración de la pila de sistema
new_struct->kernel_esp = (unsigned long)&new_union->stack[KERNEL_STACK_SIZE - 0x12];
// reescribir contexto hardware
/*
|--------|
| EIP | <- sobreescribimos con la nueva función
|--------|
| CS |
|--------|
| FLAGS |
|--------|
| ESP | <- sobreescribvimos con la nueva pila
|--------|
| SS |
|--------|
*/
//new_union->stack[KERNEL_STACK_SIZE - 0x2] = (unsigned long) parameter;
/*
%ebp
@ret
param1
*/
/*
%ebp
param1
*/
unsigned long *user_stack = (first_consecutive) << 12;
user_stack[N*1024 - 1] = (unsigned long) parameter;
user_stack[N*1024 - 2] = (unsigned long) function;
new_struct->base_stack = user_stack;
new_struct->stack_size = N;
new_union->stack[KERNEL_STACK_SIZE - 0x2] = (unsigned long) (user_stack + N*1024 - 2);
new_union->stack[KERNEL_STACK_SIZE - 0x5] = (unsigned long) function;
update_process_state_rr(new_struct, &readyqueue);
// añadir elementos a la pila de usuario
return 0;
}
sem_t* sys_sem_create(int initial_value) {
// comprobamos que initial_value no es negativo
if (initial_value < 0)
{
return NULL;
}
// comprobamos que quedan semáforos libres
int i;
for (i = 0; i < MAX_SEMAFOROS; ++i)
{
if (semaforos[i].owner == NULL)
{
break;
}
}
if (i == MAX_SEMAFOROS)
{
return NULL;
}
// inicializamos el semáforo
semaforos[i].value = initial_value;
semaforos[i].owner = current();
INIT_LIST_HEAD(&semaforos[i].blocked);
return &semaforos[i];
}
int sys_sem_wait(sem_t* s)
{
// comprobamos que el semáforo no es nulo
if (s == NULL)
{
return -EINVAL;
}
// decrementamos el contador del semáforo
s->value--;
// si el contador es negativo, bloqueamos el proceso
if (s->value < 0)
{
update_process_state_rr(current(), &s->blocked);
sched_next_rr();
}
return 0;
}
int sys_sem_signal(sem_t* s)
{
// comprobamos que el semáforo no es nulo
if (s == NULL)
{
return -EINVAL;
}
// incrementamos el contador del semáforo
s->value++;
// si el contador es negativo, desbloqueamos el primer proceso bloqueado
if (s->value <= 0)
{
struct list_head *first = list_first(&s->blocked);
struct task_struct *new_task = list_head_to_task_struct(first);
update_process_state_rr(new_task, &readyqueue);
}
return 0;
}
int sys_sem_destroy(sem_t* s)
{
// comprobamos que el semáforo no es nulo
if (s == NULL)
{
return -EINVAL;
}
// comprobamos que el semáforo pertenece al proceso actual
if (s->owner != current())
{
return -EPERM;
}
// comprobamos que no hay procesos bloqueados
if (!list_empty(&s->blocked))
{
return -EBUSY;
}
// liberamos el semáforo
s->owner = NULL;
return 0;
}
char* sys_mem_reg_get(int num_pages)
{
// allocata num_pages páginas consecutivas en el espacio de usuario
// devolver la dirección virtual de la primera página
// si no hay suficiente memoria, devolver NULL
// comprobar que num_pages es positivo
if (num_pages <= 0)
{
return NULL;
}
// comprobar que quedan páginas libres
int num_consecutives = 0;
int first_consecutive = -1;
int found = 0;
page_table_entry *pag_table = get_PT(current());
for (int i = 0; i < TOTAL_PAGES; ++i)
{
if (!found)
{
if (pag_table[i].bits.present == 0)
{
if (num_consecutives == 0)
{
first_consecutive = i;
}
if (++num_consecutives == num_pages)
{
found = 1;
}
}
else
{
num_consecutives = 0;
}
}
}
if (!found) // mo hay páginas disponibles para el stack
{
return NULL;
}
// allocatar las N páginas consecutivas
for (int i = 0; i <= num_pages; ++i)
{
int new_frame = alloc_frame();
if (new_frame != -1)
{
set_ss_pag(pag_table, first_consecutive + i, new_frame);
}
else // dealocatar todo si no queda memoria física
{
// hacemos el bucle hacia atrás
for (; i >= 0; --i)
{
free_frame(get_frame(pag_table, first_consecutive + i));
del_ss_pag(pag_table, first_consecutive + i);
}
return NULL;
}
}
((int *)first_consecutive)[0] = num_pages;
return (char *)((first_consecutive + 1) << 12);
}
int sys_mem_reg_del(char* m)
{
// elimina la región previamente allocatada en m liberando todos los recursos
// si m no es una dirección válida, devolver -1
// comprobar que m es una dirección válida
if (get_frame(get_PT(current()), (unsigned long)m >> 12) == -1)
{
return -EINVAL;
}
// liberar las páginas
page_table_entry *pag_table = get_PT(current());
int *full_pages = (int *)(((unsigned long)m >> 12) + 1);
int pages_to_dealloc = full_pages[0];
for (int i = 0; i < pages_to_dealloc; ++i)
{
free_frame(get_frame(pag_table, ((unsigned long)m >> 12) - 1 + i));
del_ss_pag(pag_table, ((unsigned long)m >> 12) - 1 + i);
}
return 0;
}