1 #include "devices/intq.h"
3 #include "threads/thread.h"
5 static int next (int pos);
6 static void wait (struct intq *q, struct thread **waiter);
7 static void signal (struct intq *q, struct thread **waiter);
9 /* Initializes interrupt queue Q. */
11 intq_init (struct intq *q)
14 q->not_full = q->not_empty = NULL;
15 q->head = q->tail = 0;
18 /* Returns true if Q is empty, false otherwise. */
20 intq_empty (const struct intq *q)
22 ASSERT (intr_get_level () == INTR_OFF);
23 return q->head == q->tail;
26 /* Returns true if Q is full, false otherwise. */
28 intq_full (const struct intq *q)
30 ASSERT (intr_get_level () == INTR_OFF);
31 return next (q->head) == q->tail;
34 /* Removes a byte from Q and returns it.
35 If Q is empty, sleeps until a byte is added.
36 When called from an interrupt handler, Q must not be empty. */
38 intq_getc (struct intq *q)
42 ASSERT (intr_get_level () == INTR_OFF);
43 while (intq_empty (q))
45 ASSERT (!intr_context ());
46 lock_acquire (&q->lock);
47 wait (q, &q->not_empty);
48 lock_release (&q->lock);
51 byte = q->buf[q->tail];
52 q->tail = next (q->tail);
53 signal (q, &q->not_full);
57 /* Adds BYTE to the end of Q.
58 If Q is full, sleeps until a byte is removed.
59 When called from an interrupt handler, Q must not be full. */
61 intq_putc (struct intq *q, uint8_t byte)
63 ASSERT (intr_get_level () == INTR_OFF);
66 ASSERT (!intr_context ());
67 lock_acquire (&q->lock);
68 wait (q, &q->not_full);
69 lock_release (&q->lock);
72 q->buf[q->head] = byte;
73 q->head = next (q->head);
74 signal (q, &q->not_empty);
77 /* Returns the position after POS within an intq. */
81 return (pos + 1) % INTQ_BUFSIZE;
84 /* WAITER must be the address of Q's not_empty or not_full
85 member. Waits until the given condition is true. */
87 wait (struct intq *q UNUSED, struct thread **waiter)
89 ASSERT (!intr_context ());
90 ASSERT (intr_get_level () == INTR_OFF);
91 ASSERT ((waiter == &q->not_empty && intq_empty (q))
92 || (waiter == &q->not_full && intq_full (q)));
94 *waiter = thread_current ();
98 /* WAITER must be the address of Q's not_empty or not_full
99 member, and the associated condition must be true. If a
100 thread is waiting for the condition, wakes it up and resets
101 the waiting thread. */
103 signal (struct intq *q UNUSED, struct thread **waiter)
105 ASSERT (intr_get_level () == INTR_OFF);
106 ASSERT ((waiter == &q->not_empty && !intq_empty (q))
107 || (waiter == &q->not_full && !intq_full (q)));
111 thread_unblock (*waiter);