Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 38 additions & 21 deletions src/devices/timer.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
/*
manipular principalmente as interrupções periódicas
conta os ticks (variavel global)
chama thread_tick a cada interrupcao
funcoes de delay (sleep, msleep, etcc)
*/

#include "devices/timer.h"
#include <debug.h>
#include <inttypes.h>
Expand All @@ -8,17 +15,14 @@
#include "threads/synch.h"
#include "threads/thread.h"

/* See [8254] for hardware details of the 8254 timer chip. */

#if TIMER_FREQ < 19
#error 8254 timer requires TIMER_FREQ >= 19
#endif
#if TIMER_FREQ > 1000
#error TIMER_FREQ <= 1000 recommended
#endif

/* Number of timer ticks since OS booted. */
static int64_t ticks;
static int64_t ticks; //variavel global

/* Number of loops per timer tick.
Initialized by timer_calibrate(). */
Expand Down Expand Up @@ -66,34 +70,42 @@ timer_calibrate (void)
printf ("%'"PRIu64" loops/s.\n", (uint64_t) loops_per_tick * TIMER_FREQ);
}

/* Returns the number of timer ticks since the OS booted. */
/* retorna qnts ticks passarm desde o boot */
int64_t
timer_ticks (void)
{
enum intr_level old_level = intr_disable ();
int64_t t = ticks;
intr_set_level (old_level);
enum intr_level old_level = intr_disable (); //desliga interrupcoes
int64_t t = ticks; // lê os ticks
intr_set_level (old_level); // retorna as interrupçoes pro estado inicial
return t;
}

/* Returns the number of timer ticks elapsed since THEN, which
should be a value once returned by timer_ticks(). */
/* FUNÇÃO PRA CALCULAR QUANTOS TICKS PASSARAM DESDE UM EVENTO ESPECÍFICO
then é o valor de ticks no instante que o evento estava acontecendo,
usando timer_ticks pega o valor do tick atual e retorna a diferença
ou seja, quantos ticks se passaram desde que o evento ocorreu */
int64_t
timer_elapsed (int64_t then)
{
return timer_ticks () - then;
return timer_ticks () - then; // calcula e retorna a diferença
}

/* Sleeps for approximately TICKS timer ticks. Interrupts must
be turned on. */
/* dorme por tantos TICKS de tempo
incialmente implementado com espera ocupada -> um loop que desperdiçava cpu
modificações na implementação: bloquear a thread até o tempo passar
checar se o tempo foi atigindo e trocar o estado da thread (blocked pra ready)
usar as interrupções pra acordar as threads que já esperaram o tempo suficiente */
void
timer_sleep (int64_t ticks)
{
int64_t start = timer_ticks ();

ASSERT (intr_get_level () == INTR_ON);
while (timer_elapsed (start) < ticks)
thread_yield ();
if (ticks <= 0){ //condicao de ticks >0 pra executar a funcao
return;
}
enum intr_level old_level = intr_disable();
int64_t sleep_ticks = (timer_ticks() + ticks); //qntd de ticks que a thread vai ficar dormindo
intr_set_level(old_level);

thread_sleep(sleep_ticks); //coloca a thread pra dormir
}

/* Sleeps for approximately MS milliseconds. Interrupts must be
Expand Down Expand Up @@ -166,12 +178,17 @@ timer_print_stats (void)
printf ("Timer: %"PRId64" ticks\n", timer_ticks ());
}

/* Timer interrupt handler. */
/* CPU INTERROMPE A THREAD ATUAL
entra no handler de interrupcao
verifica threads dormindo
acordar threads
thread_unblock */
static void
timer_interrupt (struct intr_frame *args UNUSED)
{
ticks++;
thread_tick ();
ticks++; //incrementa a variavel global de ticks
thread_wake_up(timer_ticks()); // acorda as threads que devem acordar nesse tick
thread_tick (); // atualiza (faz yield -> schedule) "chama o schedule"
}

/* Returns true if LOOPS iterations waits for more than one timer
Expand Down
47 changes: 38 additions & 9 deletions src/lib/kernel/list.c
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,13 @@ is_tail (struct list_elem *elem)
return elem != NULL && elem->prev != NULL && elem->next == NULL;
}

/* Initializes LIST as an empty list. */
/* INICIALIZAR UMA LISTA VAZIA!
essa função cria a estrutura head <-> list pra cada lista
o lixo de memória vira uma lista com a estrutura necessária:
*prepara a cabeça da lista;
*prepara a cauda da lista;
*prepara os ponteiross internos.
*/
void
list_init (struct list *list)
{
Expand All @@ -67,15 +73,20 @@ list_init (struct list *list)
list->tail.next = NULL;
}

/* Returns the beginning of LIST. */
/* RETORNA O PRIMEIRO ELEMENTO DA LISTA
após o cabeçalho, retorna o primeiro elemento real da lista

*/
struct list_elem *
list_begin (struct list *list)
{
ASSERT (list != NULL);
return list->head.next;
}

/* Returns the element after ELEM in its list. If ELEM is the
/* PRÓXIMO elemento da lista -> retorna o elemento seguinte
dá erro se o elemento for a cauda, já que o próximo é nulo.
Returns the element after ELEM in its list. If ELEM is the
last element in its list, returns the list tail. Results are
undefined if ELEM is itself a list tail. */
struct list_elem *
Expand All @@ -85,7 +96,7 @@ list_next (struct list_elem *elem)
return elem->next;
}

/* Returns LIST's tail.
/* retorna TAIL

list_end() is often used in iterating through a list from
front to back. See the big comment at the top of list.h for
Expand Down Expand Up @@ -162,16 +173,34 @@ list_tail (struct list *list)
return &list->tail;
}

/* Inserts ELEM just before BEFORE, which may be either an
interior element or a tail. The latter case is equivalent to
list_push_back(). */
/* INSERE ELEM antes de before
supondo head <-> A <-> B <-> tail, para inserir X antes de B,
4 ponteiros ajustados
before é um ponteiro para um list_elem que já está numa lista (ou o tail)
before indica a posição onde se deseja inserir o novo elemento
considerando-se que o elemento virá antes de before.

before = B e elem = X
antes da inserção, os ponteiros são
pra A:
prev -> head
next -> B
pra B:
prev -> A
next -> tail

como before = B, before->prev = A
assim, ao inserir X, teremos elem->prev = A (before->prev)
e elem->next igual ao B (before)
before->prev->next = A->next = x (elem)
*/
void
list_insert (struct list_elem *before, struct list_elem *elem)
list_insert (struct list_elem *before, struct list_elem *elem) //recebe um ponteiro e uma lista
{
ASSERT (is_interior (before) || is_tail (before));
ASSERT (elem != NULL);

elem->prev = before->prev;
elem->prev = before->prev;
elem->next = before;
before->prev->next = elem;
before->prev = elem;
Expand Down
36 changes: 36 additions & 0 deletions src/threads/fixed_point.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* biblioteca aritmetica pra ponto fixo que o mlfq precisa
pintOS não tem suporte a float dentro do kernel, então essa bib
serve pra realizar os cálculos envolvendo */

#ifndef THREADS_FIXED_POINT_H
#define THREADS_FIXED_POINT_H

typedef int fixed_point; //alias

//17 bits pra parte inteira e 14 bits pra parte fracionária
#define F (1<<14) /*escala 17.14 -- para realizar operações de priority do advenced scheduler*/

//conversao de int pra ponto fixo
#define INT_FP(n) ((n)*F)

//conversao de ponto fixo pra inteiro (truncado)
#define FP_INT(x) ((x)/F)

//conversao de ponto fixo pra inteiro (arredondado)
#define FP_INT_ROUND(x) ((x)>=0?((x)+F/2)/F:((x)-F/2)/F)

//OPERACOES ARITMETICAS
/* Adição e subtração */
#define FP_ADD(x, y) ((x) + (y)) //soma dois fixed_point
#define FP_SUB(x, y) ((x) - (y))
#define FP_ADD_INT(x, n) ((x) + (n) * F) //soma um fixed_point com um inteiro
#define FP_SUB_INT(x, n) ((x) - (n) * F)

/* Multiplicação e divisão */
#define FP_MUL(x, y) ((fixed_point)(((int64_t)(x)) * (y) / F))
#define FP_DIV(x, y) ((fixed_point)(((int64_t)(x)) * F / (y)))
#define FP_MUL_INT(x, n) ((x) * (n))
#define FP_DIV_INT(x, n) ((x) / (n))


#endif
4 changes: 4 additions & 0 deletions src/threads/synch.c
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,10 @@ lock_release (struct lock *lock)

lock->holder = NULL;
sema_up (&lock->semaphore);

if (!intr_context())
thread_yield(); //cede CPU se thread de maior prioridade for desbloqueada

}

/* Returns true if the current thread holds LOCK, false
Expand Down
Loading