code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
/* hex-dump.c
Prints files specified on command line to the console in hex. */
#include <stdio.h>
#include <syscall.h>
int
main (int argc, char *argv[])
{
bool success = true;
int i;
for (i = 1; i < argc; i++)
{
int fd = open (argv[i]);
if (fd < 0)
{
printf ("%s: open failed\n", argv[i]);
success = false;
continue;
}
for (;;)
{
char buffer[1024];
int pos = tell (fd);
int bytes_read = read (fd, buffer, sizeof buffer);
if (bytes_read == 0)
break;
hex_dump (pos, buffer, bytes_read, true);
}
close (fd);
}
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 10cm | trunk/10cm/pintos/src/examples/hex-dump.c | C | oos | 732 |
/* ls.c
Lists the contents of the directory or directories named on
the command line, or of the current directory if none are
named.
By default, only the name of each file is printed. If "-l" is
given as the first argument, the type, size, and inumber of
each file is also printed. This won't work until project 4. */
#include <syscall.h>
#include <stdio.h>
#include <string.h>
static bool
list_dir (const char *dir, bool verbose)
{
int dir_fd = open (dir);
if (dir_fd == -1)
{
printf ("%s: not found\n", dir);
return false;
}
if (isdir (dir_fd))
{
char name[READDIR_MAX_LEN];
printf ("%s", dir);
if (verbose)
printf (" (inumber %d)", inumber (dir_fd));
printf (":\n");
while (readdir (dir_fd, name))
{
printf ("%s", name);
if (verbose)
{
char full_name[128];
int entry_fd;
snprintf (full_name, sizeof full_name, "%s/%s", dir, name);
entry_fd = open (full_name);
printf (": ");
if (entry_fd != -1)
{
if (isdir (entry_fd))
printf ("directory");
else
printf ("%d-byte file", filesize (entry_fd));
printf (", inumber %d", inumber (entry_fd));
}
else
printf ("open failed");
close (entry_fd);
}
printf ("\n");
}
}
else
printf ("%s: not a directory\n", dir);
close (dir_fd);
return true;
}
int
main (int argc, char *argv[])
{
bool success = true;
bool verbose = false;
if (argc > 1 && !strcmp (argv[1], "-l"))
{
verbose = true;
argv++;
argc--;
}
if (argc <= 1)
success = list_dir (".", verbose);
else
{
int i;
for (i = 1; i < argc; i++)
if (!list_dir (argv[i], verbose))
success = false;
}
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 10cm | trunk/10cm/pintos/src/examples/ls.c | C | oos | 2,066 |
/* pwd.c
Prints the absolute name of the present working directory. */
#include <syscall.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
static bool getcwd (char *cwd, size_t cwd_size);
int
main (void)
{
char cwd[128];
if (getcwd (cwd, sizeof cwd))
{
printf ("%s\n", cwd);
return EXIT_SUCCESS;
}
else
{
printf ("error\n");
return EXIT_FAILURE;
}
}
/* Stores the inode number for FILE_NAME in *INUM.
Returns true if successful, false if the file could not be
opened. */
static bool
get_inumber (const char *file_name, int *inum)
{
int fd = open (file_name);
if (fd >= 0)
{
*inum = inumber (fd);
close (fd);
return true;
}
else
return false;
}
/* Prepends PREFIX to the characters stored in the final *DST_LEN
bytes of the DST_SIZE-byte buffer that starts at DST.
Returns true if successful, false if adding that many
characters, plus a null terminator, would overflow the buffer.
(No null terminator is actually added or depended upon, but
its space is accounted for.) */
static bool
prepend (const char *prefix,
char *dst, size_t *dst_len, size_t dst_size)
{
size_t prefix_len = strlen (prefix);
if (prefix_len + *dst_len + 1 <= dst_size)
{
*dst_len += prefix_len;
memcpy ((dst + dst_size) - *dst_len, prefix, prefix_len);
return true;
}
else
return false;
}
/* Stores the current working directory, as a null-terminated
string, in the CWD_SIZE bytes in CWD.
Returns true if successful, false on error. Errors include
system errors, directory trees deeper than MAX_LEVEL levels,
and insufficient space in CWD. */
static bool
getcwd (char *cwd, size_t cwd_size)
{
size_t cwd_len = 0;
#define MAX_LEVEL 20
char name[MAX_LEVEL * 3 + 1 + READDIR_MAX_LEN + 1];
char *namep;
int child_inum;
/* Make sure there's enough space for at least "/". */
if (cwd_size < 2)
return false;
/* Get inumber for current directory. */
if (!get_inumber (".", &child_inum))
return false;
namep = name;
for (;;)
{
int parent_inum, parent_fd;
/* Compose "../../../..", etc., in NAME. */
if ((namep - name) > MAX_LEVEL * 3)
return false;
*namep++ = '.';
*namep++ = '.';
*namep = '\0';
/* Open directory. */
parent_fd = open (name);
if (parent_fd < 0)
return false;
*namep++ = '/';
/* If parent and child have the same inumber,
then we've arrived at the root. */
parent_inum = inumber (parent_fd);
if (parent_inum == child_inum)
break;
/* Find name of file in parent directory with the child's
inumber. */
for (;;)
{
int test_inum;
if (!readdir (parent_fd, namep) || !get_inumber (name, &test_inum))
{
close (parent_fd);
return false;
}
if (test_inum == child_inum)
break;
}
close (parent_fd);
/* Prepend "/name" to CWD. */
if (!prepend (namep - 1, cwd, &cwd_len, cwd_size))
return false;
/* Move up. */
child_inum = parent_inum;
}
/* Finalize CWD. */
if (cwd_len > 0)
{
/* Move the string to the beginning of CWD,
and null-terminate it. */
memmove (cwd, (cwd + cwd_size) - cwd_len, cwd_len);
cwd[cwd_len] = '\0';
}
else
{
/* Special case for the root. */
strlcpy (cwd, "/", cwd_size);
}
return true;
}
| 10cm | trunk/10cm/pintos/src/examples/pwd.c | C | oos | 3,578 |
#include <stdio.h>
#include <syscall.h>
int
main (int argc, char **argv)
{
int i;
for (i = 0; i < argc; i++)
printf ("%s ", argv[i]);
printf ("\n");
return EXIT_SUCCESS;
}
| 10cm | trunk/10cm/pintos/src/examples/echo.c | C | oos | 187 |
/* mcp.c
Copies one file to another, using mmap. */
#include <stdio.h>
#include <string.h>
#include <syscall.h>
int
main (int argc, char *argv[])
{
int in_fd, out_fd;
mapid_t in_map, out_map;
void *in_data = (void *) 0x10000000;
void *out_data = (void *) 0x20000000;
int size;
if (argc != 3)
{
printf ("usage: cp OLD NEW\n");
return EXIT_FAILURE;
}
/* Open input file. */
in_fd = open (argv[1]);
if (in_fd < 0)
{
printf ("%s: open failed\n", argv[1]);
return EXIT_FAILURE;
}
size = filesize (in_fd);
/* Create and open output file. */
if (!create (argv[2], size))
{
printf ("%s: create failed\n", argv[2]);
return EXIT_FAILURE;
}
out_fd = open (argv[2]);
if (out_fd < 0)
{
printf ("%s: open failed\n", argv[2]);
return EXIT_FAILURE;
}
/* Map files. */
in_map = mmap (in_fd, in_data);
if (in_map == MAP_FAILED)
{
printf ("%s: mmap failed\n", argv[1]);
return EXIT_FAILURE;
}
out_map = mmap (out_fd, out_data);
if (out_map == MAP_FAILED)
{
printf ("%s: mmap failed\n", argv[2]);
return EXIT_FAILURE;
}
/* Copy files. */
memcpy (out_data, in_data, size);
/* Unmap files (optional). */
munmap (in_map);
munmap (out_map);
return EXIT_SUCCESS;
}
| 10cm | trunk/10cm/pintos/src/examples/mcp.c | C | oos | 1,329 |
/* cat.c
Copies one file to another. */
#include <stdio.h>
#include <syscall.h>
int
main (int argc, char *argv[])
{
int in_fd, out_fd;
if (argc != 3)
{
printf ("usage: cp OLD NEW\n");
return EXIT_FAILURE;
}
/* Open input file. */
in_fd = open (argv[1]);
if (in_fd < 0)
{
printf ("%s: open failed\n", argv[1]);
return EXIT_FAILURE;
}
/* Create and open output file. */
if (!create (argv[2], filesize (in_fd)))
{
printf ("%s: create failed\n", argv[2]);
return EXIT_FAILURE;
}
out_fd = open (argv[2]);
if (out_fd < 0)
{
printf ("%s: open failed\n", argv[2]);
return EXIT_FAILURE;
}
/* Copy data. */
for (;;)
{
char buffer[1024];
int bytes_read = read (in_fd, buffer, sizeof buffer);
if (bytes_read == 0)
break;
if (write (out_fd, buffer, bytes_read) != bytes_read)
{
printf ("%s: write failed\n", argv[2]);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
| 10cm | trunk/10cm/pintos/src/examples/cp.c | C | oos | 1,048 |
/* mcat.c
Prints files specified on command line to the console, using
mmap. */
#include <stdio.h>
#include <syscall.h>
int
main (int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
{
int fd;
mapid_t map;
void *data = (void *) 0x10000000;
int size;
/* Open input file. */
fd = open (argv[i]);
if (fd < 0)
{
printf ("%s: open failed\n", argv[i]);
return EXIT_FAILURE;
}
size = filesize (fd);
/* Map files. */
map = mmap (fd, data);
if (map == MAP_FAILED)
{
printf ("%s: mmap failed\n", argv[i]);
return EXIT_FAILURE;
}
/* Write file to console. */
write (STDOUT_FILENO, data, size);
/* Unmap files (optional). */
munmap (map);
}
return EXIT_SUCCESS;
}
| 10cm | trunk/10cm/pintos/src/examples/mcat.c | C | oos | 855 |
/* halt.c
Simple program to test whether running a user program works.
Just invokes a system call that shuts down the operating system. */
#include <syscall.h>
int
main (void)
{
halt ();
/* not reached */
}
| 10cm | trunk/10cm/pintos/src/examples/halt.c | C | oos | 223 |
/* rm.c
Removes files specified on command line. */
#include <stdio.h>
#include <syscall.h>
int
main (int argc, char *argv[])
{
bool success = true;
int i;
for (i = 1; i < argc; i++)
if (!remove (argv[i]))
{
printf ("%s: remove failed\n", argv[i]);
success = false;
}
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 10cm | trunk/10cm/pintos/src/examples/rm.c | C | oos | 368 |
/* mkdir.c
Creates a directory. */
#include <stdio.h>
#include <syscall.h>
int
main (int argc, char *argv[])
{
if (argc != 2)
{
printf ("usage: %s DIRECTORY\n", argv[0]);
return EXIT_FAILURE;
}
if (!mkdir (argv[1]))
{
printf ("%s: mkdir failed\n", argv[1]);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 10cm | trunk/10cm/pintos/src/examples/mkdir.c | C | oos | 363 |
/* Insult.c
This is a version of the famous CS 107 random sentence
generator. I wrote a program that reads a grammar definition
file and writes a C file containing that grammar as hard code
static C strings. Thus the majority of the code below in
machine generated and totally unreadable. The arrays created
are specially designed to make generating the sentences as
easy as possible.
Originally by Greg Hutchins, March 1998.
Modified by Ben Pfaff for Pintos, Sept 2004. */
char *start[] =
{ "You", "1", "5", ".", "May", "13", ".", "With", "the", "19", "of", "18",
",", "may", "13", "."
};
char startLoc[] = { 3, 0, 4, 7, 16 };
char *adj[] = { "3", "4", "2", ",", "1" };
char adjLoc[] = { 3, 0, 1, 2, 5 };
char *adj3[] = { "3", "4" };
char adj3Loc[] = { 2, 0, 1, 2 };
char *adj1[] =
{ "lame", "dried", "up", "par-broiled", "bloated", "half-baked", "spiteful",
"egotistical", "ungrateful", "stupid", "moronic", "fat", "ugly", "puny", "pitiful",
"insignificant", "blithering", "repulsive", "worthless", "blundering", "retarded",
"useless", "obnoxious", "low-budget", "assinine", "neurotic", "subhuman", "crochety",
"indescribable", "contemptible", "unspeakable", "sick", "lazy", "good-for-nothing",
"slutty", "mentally-deficient", "creepy", "sloppy", "dismal", "pompous", "pathetic",
"friendless", "revolting", "slovenly", "cantankerous", "uncultured", "insufferable",
"gross", "unkempt", "defective", "crumby"
};
char adj1Loc[] =
{ 50, 0, 1, 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 };
char *adj2[] =
{ "putrefied", "festering", "funky", "moldy", "leprous", "curdled", "fetid",
"slimy", "crusty", "sweaty", "damp", "deranged", "smelly", "stenchy", "malignant",
"noxious", "grimy", "reeky", "nasty", "mutilated", "sloppy", "gruesome", "grisly",
"sloshy", "wormy", "mealy", "spoiled", "contaminated", "rancid", "musty",
"fly-covered", "moth-eaten", "decaying", "decomposed", "freeze-dried", "defective",
"petrified", "rotting", "scabrous", "hirsute"
};
char adj2Loc[] =
{ 40, 0, 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 };
char *name[] =
{ "10", ",", "bad", "excuse", "for", "6", ",", "6", "for", "brains", ",",
"4", "11", "8", "for", "brains", "offspring", "of", "a", "motherless", "10", "7", "6",
"7", "4", "11", "8"
};
char nameLoc[] = { 7, 0, 1, 6, 10, 16, 21, 23, 27 };
char *stuff[] =
{ "shit", "toe", "jam", "filth", "puss", "earwax", "leaf", "clippings",
"bat", "guano", "mucus", "fungus", "mung", "refuse", "earwax", "spittoon", "spittle",
"phlegm"
};
char stuffLoc[] = { 14, 0, 1, 3, 4, 5, 6, 8, 10, 11, 12, 13, 14, 15, 17, 18 };
char *noun_and_prep[] =
{ "bit", "of", "piece", "of", "vat", "of", "lump", "of", "crock", "of",
"ball", "of", "tub", "of", "load", "of", "bucket", "of", "mound", "of", "glob", "of", "bag",
"of", "heap", "of", "mountain", "of", "load", "of", "barrel", "of", "sack", "of", "blob", "of",
"pile", "of", "truckload", "of", "vat", "of"
};
char noun_and_prepLoc[] =
{ 21, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36,
38, 40, 42 };
char *organics[] =
{ "droppings", "mung", "zits", "puckies", "tumors", "cysts", "tumors",
"livers", "froth", "parts", "scabs", "guts", "entrails", "blubber", "carcuses", "gizards",
"9"
};
char organicsLoc[] =
{ 17, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };
char *body_parts[] =
{ "kidneys", "genitals", "buttocks", "earlobes", "innards", "feet"
};
char body_partsLoc[] = { 6, 0, 1, 2, 3, 4, 5, 6 };
char *noun[] =
{ "pop", "tart", "warthog", "twinkie", "barnacle", "fondue", "pot",
"cretin", "fuckwad", "moron", "ass", "neanderthal", "nincompoop", "simpleton", "11"
};
char nounLoc[] = { 13, 0, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
char *animal[] =
{ "donkey", "llama", "dingo", "lizard", "gekko", "lemur", "moose", "camel",
"goat", "eel"
};
char animalLoc[] = { 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
char *good_verb[] =
{ "love", "cuddle", "fondle", "adore", "smooch", "hug", "caress", "worship",
"look", "at", "touch"
};
char good_verbLoc[] = { 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 };
char *curse[] =
{ "14", "20", "23", "14", "17", "20", "23", "14", "find", "your", "9",
"suddenly", "delectable", "14", "and", "14", "seek", "a", "battleground", "23"
};
char curseLoc[] = { 4, 0, 3, 7, 13, 20 };
char *afflictors[] =
{ "15", "21", "15", "21", "15", "21", "15", "21", "a", "22", "Rush",
"Limbaugh", "the", "hosts", "of", "Hades"
};
char afflictorsLoc[] = { 6, 0, 2, 4, 6, 8, 12, 16 };
char *quantity[] =
{ "a", "4", "hoard", "of", "a", "4", "pack", "of", "a", "truckload", "of",
"a", "swarm", "of", "many", "an", "army", "of", "a", "4", "heard", "of", "a", "4",
"platoon", "of", "a", "4", "and", "4", "group", "of", "16"
};
char quantityLoc[] = { 10, 0, 4, 8, 11, 14, 15, 18, 22, 26, 32, 33 };
char *numbers[] =
{ "a", "thousand", "three", "million", "ninty-nine", "nine-hundred,",
"ninty-nine", "forty-two", "a", "gazillion", "sixty-eight", "times", "thirty-three"
};
char numbersLoc[] = { 7, 0, 2, 4, 5, 7, 8, 10, 13 };
char *adv[] =
{ "viciously", "manicly", "merrily", "happily", ",", "with", "the", "19",
"of", "18", ",", "gleefully", ",", "with", "much", "ritualistic", "celebration", ",",
"franticly"
};
char advLoc[] = { 8, 0, 1, 2, 3, 4, 11, 12, 18, 19 };
char *metaphor[] =
{ "an", "irate", "manticore", "Thor's", "belch", "Alah's", "fist", "16",
"titans", "a", "particularly", "vicious", "she-bear", "in", "the", "midst", "of", "her",
"menstrual", "cycle", "a", "pissed-off", "Jabberwock"
};
char metaphorLoc[] = { 6, 0, 3, 5, 7, 9, 20, 23 };
char *force[] = { "force", "fury", "power", "rage" };
char forceLoc[] = { 4, 0, 1, 2, 3, 4 };
char *bad_action[] =
{ "spit", "shimmy", "slobber", "find", "refuge", "find", "shelter", "dance",
"retch", "vomit", "defecate", "erect", "a", "strip", "mall", "build", "a", "26", "have", "a",
"religious", "experience", "discharge", "bodily", "waste", "fart", "dance", "drool",
"lambada", "spill", "16", "rusty", "tacks", "bite", "you", "sneeze", "sing", "16",
"campfire", "songs", "smite", "you", "16", "times", "construct", "a", "new", "home", "throw",
"a", "party", "procreate"
};
char bad_actionLoc[] =
{ 25, 0, 1, 2, 3, 5, 7, 8, 9, 10, 11, 15, 18, 22, 25, 26, 27, 28, 29, 33,
35, 36, 40, 44, 48, 51, 52 };
char *beasties[] =
{ "yaks", "22", "maggots", "22", "cockroaches", "stinging", "scorpions",
"fleas", "22", "weasels", "22", "gnats", "South", "American", "killer", "bees", "spiders",
"4", "monkeys", "22", "wiener-dogs", "22", "rats", "22", "wolverines", "4", ",", "22",
"pit-fiends"
};
char beastiesLoc[] =
{ 14, 0, 1, 3, 5, 7, 8, 10, 12, 16, 17, 19, 21, 23, 25, 29 };
char *condition[] =
{ "frothing", "manic", "crazed", "plague-ridden", "disease-carrying",
"biting", "rabid", "blood-thirsty", "ravaging", "slavering"
};
char conditionLoc[] = { 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
char *place[] =
{ "in", "24", "25", "upon", "your", "mother's", "grave", "on", "24", "best",
"rug", "in", "the", "26", "you", "call", "home", "upon", "your", "heinie"
};
char placeLoc[] = { 5, 0, 3, 7, 11, 17, 20 };
char *relation[] =
{ "your", "your", "your", "your", "father's", "your", "mother's", "your",
"grandma's"
};
char relationLoc[] = { 6, 0, 1, 2, 3, 5, 7, 9 };
char *in_something[] =
{ "entrails", "anal", "cavity", "shoes", "house", "pantry", "general",
"direction", "pants", "bed"
};
char in_somethingLoc[] = { 8, 0, 1, 3, 4, 5, 6, 8, 9, 10 };
char *bad_place[] =
{ "rat", "hole", "sewer", "toxic", "dump", "oil", "refinery", "landfill",
"porto-pottie"
};
char bad_placeLoc[] = { 6, 0, 2, 3, 5, 7, 8, 9 };
char **daGrammar[27];
char *daGLoc[27];
static void
init_grammar (void)
{
daGrammar[0] = start;
daGLoc[0] = startLoc;
daGrammar[1] = adj;
daGLoc[1] = adjLoc;
daGrammar[2] = adj3;
daGLoc[2] = adj3Loc;
daGrammar[3] = adj1;
daGLoc[3] = adj1Loc;
daGrammar[4] = adj2;
daGLoc[4] = adj2Loc;
daGrammar[5] = name;
daGLoc[5] = nameLoc;
daGrammar[6] = stuff;
daGLoc[6] = stuffLoc;
daGrammar[7] = noun_and_prep;
daGLoc[7] = noun_and_prepLoc;
daGrammar[8] = organics;
daGLoc[8] = organicsLoc;
daGrammar[9] = body_parts;
daGLoc[9] = body_partsLoc;
daGrammar[10] = noun;
daGLoc[10] = nounLoc;
daGrammar[11] = animal;
daGLoc[11] = animalLoc;
daGrammar[12] = good_verb;
daGLoc[12] = good_verbLoc;
daGrammar[13] = curse;
daGLoc[13] = curseLoc;
daGrammar[14] = afflictors;
daGLoc[14] = afflictorsLoc;
daGrammar[15] = quantity;
daGLoc[15] = quantityLoc;
daGrammar[16] = numbers;
daGLoc[16] = numbersLoc;
daGrammar[17] = adv;
daGLoc[17] = advLoc;
daGrammar[18] = metaphor;
daGLoc[18] = metaphorLoc;
daGrammar[19] = force;
daGLoc[19] = forceLoc;
daGrammar[20] = bad_action;
daGLoc[20] = bad_actionLoc;
daGrammar[21] = beasties;
daGLoc[21] = beastiesLoc;
daGrammar[22] = condition;
daGLoc[22] = conditionLoc;
daGrammar[23] = place;
daGLoc[23] = placeLoc;
daGrammar[24] = relation;
daGLoc[24] = relationLoc;
daGrammar[25] = in_something;
daGLoc[25] = in_somethingLoc;
daGrammar[26] = bad_place;
daGLoc[26] = bad_placeLoc;
}
#include <ctype.h>
#include <debug.h>
#include <random.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syscall.h>
void expand (int num, char **grammar[], char *location[], int handle);
static void
usage (int ret_code, const char *message, ...) PRINTF_FORMAT (2, 3);
static void
usage (int ret_code, const char *message, ...)
{
va_list args;
if (message != NULL)
{
va_start (args, message);
vprintf (message, args);
va_end (args);
}
printf ("\n"
"Usage: insult [OPTION]...\n"
"Prints random insults to screen.\n\n"
" -h: this help message\n"
" -s <integer>: set the random seed (default 4951)\n"
" -n <integer>: choose number of insults (default 4)\n"
" -f <file>: redirect output to <file>\n");
exit (ret_code);
}
int
main (int argc, char *argv[])
{
int sentence_cnt, new_seed, i, file_flag, sent_flag, seed_flag;
int handle;
new_seed = 4951;
sentence_cnt = 4;
file_flag = 0;
seed_flag = 0;
sent_flag = 0;
handle = STDOUT_FILENO;
for (i = 1; i < argc; i++)
{
if (strcmp (argv[1], "-h") == 0)
usage (0, NULL);
else if (strcmp (argv[i], "-s") == 0)
{
if (seed_flag++)
usage (-1, "Can't have more than one seed");
if (++i >= argc)
usage (-1, "Missing value for -s");
new_seed = atoi (argv[i]);
}
else if (strcmp (argv[i], "-n") == 0)
{
if (sent_flag++)
usage (-1, "Can't have more than one sentence option");
if (++i >= argc)
usage (-1, "Missing value for -n");
sentence_cnt = atoi (argv[i]);
if (sentence_cnt < 1)
usage (-1, "Must have at least one sentence");
}
else if (strcmp (argv[i], "-f") == 0)
{
if (file_flag++)
usage (-1, "Can't have more than one output file");
if (++i >= argc)
usage (-1, "Missing value for -f");
/* Because files have fixed length in the basic Pintos
file system, the 0 argument means that this option
will not be useful until project 4 is
implemented. */
create (argv[i], 0);
handle = open (argv[i]);
if (handle < 0)
{
printf ("%s: open failed\n", argv[i]);
return EXIT_FAILURE;
}
}
else
usage (-1, "Unrecognized flag");
}
init_grammar ();
random_init (new_seed);
hprintf (handle, "\n");
for (i = 0; i < sentence_cnt; i++)
{
hprintf (handle, "\n");
expand (0, daGrammar, daGLoc, handle);
hprintf (handle, "\n\n");
}
if (file_flag)
close (handle);
return EXIT_SUCCESS;
}
void
expand (int num, char **grammar[], char *location[], int handle)
{
char *word;
int i, which, listStart, listEnd;
which = random_ulong () % location[num][0] + 1;
listStart = location[num][which];
listEnd = location[num][which + 1];
for (i = listStart; i < listEnd; i++)
{
word = grammar[num][i];
if (!isdigit (*word))
{
if (!ispunct (*word))
hprintf (handle, " ");
hprintf (handle, "%s", word);
}
else
expand (atoi (word), grammar, location, handle);
}
}
| 10cm | trunk/10cm/pintos/src/examples/insult.c | C | oos | 12,544 |
/* cat.c
Prints files specified on command line to the console. */
#include <stdio.h>
#include <syscall.h>
int
main (int argc, char *argv[])
{
bool success = true;
int i;
for (i = 1; i < argc; i++)
{
int fd = open (argv[i]);
if (fd < 0)
{
printf ("%s: open failed\n", argv[i]);
success = false;
continue;
}
for (;;)
{
char buffer[1024];
int bytes_read = read (fd, buffer, sizeof buffer);
if (bytes_read == 0)
break;
write (STDOUT_FILENO, buffer, bytes_read);
}
close (fd);
}
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 10cm | trunk/10cm/pintos/src/examples/cat.c | C | oos | 690 |
/* sort.c
Test program to sort a large number of integers.
Intention is to stress virtual memory system.
Ideally, we could read the unsorted array off of the file
system, and store the result back to the file system! */
#include <stdio.h>
/* Size of array to sort. */
#define SORT_SIZE 128
int
main (void)
{
/* Array to sort. Static to reduce stack usage. */
static int array[SORT_SIZE];
int i, j, tmp;
/* First initialize the array in descending order. */
for (i = 0; i < SORT_SIZE; i++)
array[i] = SORT_SIZE - i - 1;
/* Then sort in ascending order. */
for (i = 0; i < SORT_SIZE - 1; i++)
for (j = 0; j < SORT_SIZE - 1 - i; j++)
if (array[j] > array[j + 1])
{
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
printf ("sort exiting with code %d\n", array[0]);
return array[0];
}
| 10cm | trunk/10cm/pintos/src/examples/bubsort.c | C | oos | 862 |
/* lineup.c
Converts a file to uppercase in-place.
Incidentally, another way to do this while avoiding the seeks
would be to open the input file, then remove() it and reopen
it under another handle. Because of Unix deletion semantics
this works fine. */
#include <ctype.h>
#include <stdio.h>
#include <syscall.h>
int
main (int argc, char *argv[])
{
char buf[1024];
int handle;
if (argc != 2)
exit (1);
handle = open (argv[1]);
if (handle < 0)
exit (2);
for (;;)
{
int n, i;
n = read (handle, buf, sizeof buf);
if (n <= 0)
break;
for (i = 0; i < n; i++)
buf[i] = toupper ((unsigned char) buf[i]);
seek (handle, tell (handle) - n);
if (write (handle, buf, n) != n)
printf ("write failed\n");
}
close (handle);
return EXIT_SUCCESS;
}
| 10cm | trunk/10cm/pintos/src/examples/lineup.c | C | oos | 852 |
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <syscall.h>
static void read_line (char line[], size_t);
static bool backspace (char **pos, char line[]);
int
main (void)
{
printf ("Shell starting...\n");
for (;;)
{
char command[80];
/* Read command. */
printf ("--");
read_line (command, sizeof command);
/* Execute command. */
if (!strcmp (command, "exit"))
break;
else if (!memcmp (command, "cd ", 3))
{
if (!chdir (command + 3))
printf ("\"%s\": chdir failed\n", command + 3);
}
else if (command[0] == '\0')
{
/* Empty command. */
}
else
{
pid_t pid = exec (command);
if (pid != PID_ERROR)
printf ("\"%s\": exit code %d\n", command, wait (pid));
else
printf ("exec failed\n");
}
}
printf ("Shell exiting.");
return EXIT_SUCCESS;
}
/* Reads a line of input from the user into LINE, which has room
for SIZE bytes. Handles backspace and Ctrl+U in the ways
expected by Unix users. On return, LINE will always be
null-terminated and will not end in a new-line character. */
static void
read_line (char line[], size_t size)
{
char *pos = line;
for (;;)
{
char c;
read (STDIN_FILENO, &c, 1);
switch (c)
{
case '\r':
*pos = '\0';
putchar ('\n');
return;
case '\b':
backspace (&pos, line);
break;
case ('U' - 'A') + 1: /* Ctrl+U. */
while (backspace (&pos, line))
continue;
break;
default:
/* Add character to line. */
if (pos < line + size - 1)
{
putchar (c);
*pos++ = c;
}
break;
}
}
}
/* If *POS is past the beginning of LINE, backs up one character
position. Returns true if successful, false if nothing was
done. */
static bool
backspace (char **pos, char line[])
{
if (*pos > line)
{
/* Back up cursor, overwrite character, back up
again. */
printf ("\b \b");
(*pos)--;
return true;
}
else
return false;
}
| 10cm | trunk/10cm/pintos/src/examples/shell.c | C | oos | 2,278 |
#include <stdio.h>
#include <stdlib.h>
#include <syscall.h>
int
main (int argc, char *argv[])
{
char buffer[128];
pid_t pid;
int retval = 0;
if (argc != 4)
{
printf ("usage: recursor <string> <depth> <waitp>\n");
exit (1);
}
/* Print args. */
printf ("%s %s %s %s\n", argv[0], argv[1], argv[2], argv[3]);
/* Execute child and wait for it to finish if requested. */
if (atoi (argv[2]) != 0)
{
snprintf (buffer, sizeof buffer,
"recursor %s %d %s", argv[1], atoi (argv[2]) - 1, argv[3]);
pid = exec (buffer);
if (atoi (argv[3]))
retval = wait (pid);
}
/* Done. */
printf ("%s %s: dying, retval=%d\n", argv[1], argv[2], retval);
exit (retval);
}
| 10cm | trunk/10cm/pintos/src/examples/recursor.c | C | oos | 743 |
/* matmult.c
Test program to do matrix multiplication on large arrays.
Intended to stress virtual memory system.
Ideally, we could read the matrices off of the file system,
and store the result back to the file system!
*/
#include <stdio.h>
#include <syscall.h>
/* You should define DIM to be large enough that the arrays
don't fit in physical memory.
Dim Memory
------ --------
16 3 kB
64 48 kB
128 192 kB
256 768 kB
512 3,072 kB
1,024 12,288 kB
2,048 49,152 kB
4,096 196,608 kB
8,192 786,432 kB
16,384 3,145,728 kB */
#define DIM 128
int A[DIM][DIM];
int B[DIM][DIM];
int C[DIM][DIM];
int
main (void)
{
int i, j, k;
/* Initialize the matrices. */
for (i = 0; i < DIM; i++)
for (j = 0; j < DIM; j++)
{
A[i][j] = i;
B[i][j] = j;
C[i][j] = 0;
}
/* Multiply matrices. */
for (i = 0; i < DIM; i++)
for (j = 0; j < DIM; j++)
for (k = 0; k < DIM; k++)
C[i][j] += A[i][k] * B[k][j];
/* Done. */
exit (C[DIM - 1][DIM - 1]);
}
| 10cm | trunk/10cm/pintos/src/examples/matmult.c | C | oos | 1,083 |
SRCDIR = ..
# Test programs to compile, and a list of sources for each.
# To add a new test, put its name on the PROGS list
# and then add a name_SRC line that lists its source files.
PROGS = cat cmp cp echo halt hex-dump ls mcat mcp mkdir pwd rm shell \
bubsort insult lineup matmult recursor
# Should work from project 2 onward.
cat_SRC = cat.c
cmp_SRC = cmp.c
cp_SRC = cp.c
echo_SRC = echo.c
halt_SRC = halt.c
hex-dump_SRC = hex-dump.c
insult_SRC = insult.c
lineup_SRC = lineup.c
ls_SRC = ls.c
recursor_SRC = recursor.c
rm_SRC = rm.c
# Should work in project 3; also in project 4 if VM is included.
bubsort_SRC = bubsort.c
matmult_SRC = matmult.c
mcat_SRC = mcat.c
mcp_SRC = mcp.c
# Should work in project 4.
mkdir_SRC = mkdir.c
pwd_SRC = pwd.c
shell_SRC = shell.c
include $(SRCDIR)/Make.config
include $(SRCDIR)/Makefile.userprog
| 10cm | trunk/10cm/pintos/src/examples/Makefile | Makefile | oos | 840 |
#ifndef DEVICES_DISK_H
#define DEVICES_DISK_H
#include <inttypes.h>
#include <stdint.h>
/* Size of a disk sector in bytes. */
#define DISK_SECTOR_SIZE 512
/* Index of a disk sector within a disk.
Good enough for disks up to 2TB. */
typedef uint32_t disk_sector_t;
/* Format specifier for printf(), e.g.:
printf ("sector=%"PRDSNu"\n", sector); */
#define PRDSNu PRIu32
void disk_init (void);
void disk_print_stats (void);
struct disk *disk_get (int chan_no, int dev_no);
disk_sector_t disk_size (struct disk *);
void disk_read (struct disk *, disk_sector_t, void *);
void disk_write (struct disk *, disk_sector_t, const void *);
#endif /* devices/disk.h */
| 10cm | trunk/10cm/pintos/src/devices/disk.h | C | oos | 669 |
#ifndef DEVICES_KBD_H
#define DEVICES_KBD_H
#include <stdint.h>
void kbd_init (void);
void kbd_print_stats (void);
#endif /* devices/kbd.h */
| 10cm | trunk/10cm/pintos/src/devices/kbd.h | C | oos | 145 |
#include "devices/kbd.h"
#include <ctype.h>
#include <debug.h>
#include <stdio.h>
#include <string.h>
#include "devices/input.h"
#include "threads/init.h"
#include "threads/interrupt.h"
#include "threads/io.h"
/* Keyboard data register port. */
#define DATA_REG 0x60
/* Current state of shift keys.
True if depressed, false otherwise. */
static bool left_shift, right_shift; /* Left and right Shift keys. */
static bool left_alt, right_alt; /* Left and right Alt keys. */
static bool left_ctrl, right_ctrl; /* Left and right Ctl keys. */
/* Status of Caps Lock.
True when on, false when off. */
static bool caps_lock;
/* Number of keys pressed. */
static int64_t key_cnt;
static intr_handler_func keyboard_interrupt;
/* Initializes the keyboard. */
void
kbd_init (void)
{
intr_register_ext (0x21, keyboard_interrupt, "8042 Keyboard");
}
/* Prints keyboard statistics. */
void
kbd_print_stats (void)
{
printf ("Keyboard: %lld keys pressed\n", key_cnt);
}
/* Maps a set of contiguous scancodes into characters. */
struct keymap
{
uint8_t first_scancode; /* First scancode. */
const char *chars; /* chars[0] has scancode first_scancode,
chars[1] has scancode first_scancode + 1,
and so on to the end of the string. */
};
/* Keys that produce the same characters regardless of whether
the Shift keys are down. Case of letters is an exception
that we handle elsewhere. */
static const struct keymap invariant_keymap[] =
{
{0x01, "\033"}, /* Escape. */
{0x0e, "\b"},
{0x0f, "\tQWERTYUIOP"},
{0x1c, "\r"},
{0x1e, "ASDFGHJKL"},
{0x2c, "ZXCVBNM"},
{0x37, "*"},
{0x39, " "},
{0x53, "\177"}, /* Delete. */
{0, NULL},
};
/* Characters for keys pressed without Shift, for those keys
where it matters. */
static const struct keymap unshifted_keymap[] =
{
{0x02, "1234567890-="},
{0x1a, "[]"},
{0x27, ";'`"},
{0x2b, "\\"},
{0x33, ",./"},
{0, NULL},
};
/* Characters for keys pressed with Shift, for those keys where
it matters. */
static const struct keymap shifted_keymap[] =
{
{0x02, "!@#$%^&*()_+"},
{0x1a, "{}"},
{0x27, ":\"~"},
{0x2b, "|"},
{0x33, "<>?"},
{0, NULL},
};
static bool map_key (const struct keymap[], unsigned scancode, uint8_t *);
static void
keyboard_interrupt (struct intr_frame *args UNUSED)
{
/* Status of shift keys. */
bool shift = left_shift || right_shift;
bool alt = left_alt || right_alt;
bool ctrl = left_ctrl || right_ctrl;
/* Keyboard scancode. */
unsigned code;
/* False if key pressed, true if key released. */
bool release;
/* Character that corresponds to `code'. */
uint8_t c;
/* Read scancode, including second byte if prefix code. */
code = inb (DATA_REG);
if (code == 0xe0)
code = (code << 8) | inb (DATA_REG);
/* Bit 0x80 distinguishes key press from key release
(even if there's a prefix). */
release = (code & 0x80) != 0;
code &= ~0x80u;
/* Interpret key. */
if (code == 0x3a)
{
/* Caps Lock. */
if (!release)
caps_lock = !caps_lock;
}
else if (map_key (invariant_keymap, code, &c)
|| (!shift && map_key (unshifted_keymap, code, &c))
|| (shift && map_key (shifted_keymap, code, &c)))
{
/* Ordinary character. */
if (!release)
{
/* Reboot if Ctrl+Alt+Del pressed. */
if (c == 0177 && ctrl && alt)
reboot ();
/* Handle Ctrl, Shift.
Note that Ctrl overrides Shift. */
if (ctrl && c >= 0x40 && c < 0x60)
{
/* A is 0x41, Ctrl+A is 0x01, etc. */
c -= 0x40;
}
else if (shift == caps_lock)
c = tolower (c);
/* Handle Alt by setting the high bit.
This 0x80 is unrelated to the one used to
distinguish key press from key release. */
if (alt)
c += 0x80;
/* Append to keyboard buffer. */
if (!input_full ())
{
key_cnt++;
input_putc (c);
}
}
}
else
{
/* Maps a keycode into a shift state variable. */
struct shift_key
{
unsigned scancode;
bool *state_var;
};
/* Table of shift keys. */
static const struct shift_key shift_keys[] =
{
{ 0x2a, &left_shift},
{ 0x36, &right_shift},
{ 0x38, &left_alt},
{0xe038, &right_alt},
{ 0x1d, &left_ctrl},
{0xe01d, &right_ctrl},
{0, NULL},
};
const struct shift_key *key;
/* Scan the table. */
for (key = shift_keys; key->scancode != 0; key++)
if (key->scancode == code)
{
*key->state_var = !release;
break;
}
}
}
/* Scans the array of keymaps K for SCANCODE.
If found, sets *C to the corresponding character and returns
true.
If not found, returns false and C is ignored. */
static bool
map_key (const struct keymap k[], unsigned scancode, uint8_t *c)
{
for (; k->first_scancode != 0; k++)
if (scancode >= k->first_scancode
&& scancode < k->first_scancode + strlen (k->chars))
{
*c = k->chars[scancode - k->first_scancode];
return true;
}
return false;
}
| 10cm | trunk/10cm/pintos/src/devices/kbd.c | C | oos | 5,504 |
#ifndef DEVICES_TIMER_H
#define DEVICES_TIMER_H
#include <round.h>
#include <stdint.h>
/* Number of timer interrupts per second. */
#define TIMER_FREQ 100
void timer_init (void);
void timer_calibrate (void);
int64_t timer_ticks (void);
int64_t timer_elapsed (int64_t);
/* Sleep and yield the CPU to other threads. */
void timer_sleep (int64_t ticks);
void timer_msleep (int64_t milliseconds);
void timer_usleep (int64_t microseconds);
void timer_nsleep (int64_t nanoseconds);
/* Busy wait. */
void timer_mdelay (int64_t milliseconds);
void timer_udelay (int64_t microseconds);
void timer_ndelay (int64_t nanoseconds);
void timer_print_stats (void);
#endif /* devices/timer.h */
| 10cm | trunk/10cm/pintos/src/devices/timer.h | C | oos | 686 |
#include "devices/input.h"
#include <debug.h>
#include "devices/intq.h"
#include "devices/serial.h"
/* Stores keys from the keyboard and serial port. */
static struct intq buffer;
/* Initializes the input buffer. */
void
input_init (void)
{
intq_init (&buffer);
}
/* Adds a key to the input buffer.
Interrupts must be off and the buffer must not be full. */
void
input_putc (uint8_t key)
{
ASSERT (intr_get_level () == INTR_OFF);
ASSERT (!intq_full (&buffer));
intq_putc (&buffer, key);
serial_notify ();
}
/* Retrieves a key from the input buffer.
If the buffer is empty, waits for a key to be pressed. */
uint8_t
input_getc (void)
{
enum intr_level old_level;
uint8_t key;
old_level = intr_disable ();
key = intq_getc (&buffer);
serial_notify ();
intr_set_level (old_level);
return key;
}
/* Returns true if the input buffer is full,
false otherwise.
Interrupts must be off. */
bool
input_full (void)
{
ASSERT (intr_get_level () == INTR_OFF);
return intq_full (&buffer);
}
| 10cm | trunk/10cm/pintos/src/devices/input.c | C | oos | 1,029 |
#ifndef RTC_H
#define RTC_H
typedef unsigned long time_t;
time_t rtc_get_time (void);
#endif
| 10cm | trunk/10cm/pintos/src/devices/rtc.h | C | oos | 96 |
#include "devices/serial.h"
#include <debug.h>
#include "devices/input.h"
#include "devices/intq.h"
#include "devices/timer.h"
#include "threads/io.h"
#include "threads/interrupt.h"
#include "threads/synch.h"
#include "threads/thread.h"
/* Register definitions for the 16550A UART used in PCs.
The 16550A has a lot more going on than shown here, but this
is all we need.
Refer to [PC16650D] for hardware information. */
/* I/O port base address for the first serial port. */
#define IO_BASE 0x3f8
/* DLAB=0 registers. */
#define RBR_REG (IO_BASE + 0) /* Receiver Buffer Reg. (read-only). */
#define THR_REG (IO_BASE + 0) /* Transmitter Holding Reg. (write-only). */
#define IER_REG (IO_BASE + 1) /* Interrupt Enable Reg.. */
/* DLAB=1 registers. */
#define LS_REG (IO_BASE + 0) /* Divisor Latch (LSB). */
#define MS_REG (IO_BASE + 1) /* Divisor Latch (MSB). */
/* DLAB-insensitive registers. */
#define IIR_REG (IO_BASE + 2) /* Interrupt Identification Reg. (read-only) */
#define FCR_REG (IO_BASE + 2) /* FIFO Control Reg. (write-only). */
#define LCR_REG (IO_BASE + 3) /* Line Control Register. */
#define MCR_REG (IO_BASE + 4) /* MODEM Control Register. */
#define LSR_REG (IO_BASE + 5) /* Line Status Register (read-only). */
/* Interrupt Enable Register bits. */
#define IER_RECV 0x01 /* Interrupt when data received. */
#define IER_XMIT 0x02 /* Interrupt when transmit finishes. */
/* Line Control Register bits. */
#define LCR_N81 0x03 /* No parity, 8 data bits, 1 stop bit. */
#define LCR_DLAB 0x80 /* Divisor Latch Access Bit (DLAB). */
/* MODEM Control Register. */
#define MCR_OUT2 0x08 /* Output line 2. */
/* Line Status Register. */
#define LSR_DR 0x01 /* Data Ready: received data byte is in RBR. */
#define LSR_THRE 0x20 /* THR Empty. */
/* Transmission mode. */
static enum { UNINIT, POLL, QUEUE } mode;
/* Data to be transmitted. */
static struct intq txq;
static void set_serial (int bps);
static void putc_poll (uint8_t);
static void write_ier (void);
static intr_handler_func serial_interrupt;
/* Initializes the serial port device for polling mode.
Polling mode busy-waits for the serial port to become free
before writing to it. It's slow, but until interrupts have
been initialized it's all we can do. */
static void
init_poll (void)
{
ASSERT (mode == UNINIT);
outb (IER_REG, 0); /* Turn off all interrupts. */
outb (FCR_REG, 0); /* Disable FIFO. */
set_serial (115200); /* 115.2 kbps, N-8-1. */
outb (MCR_REG, MCR_OUT2); /* Required to enable interrupts. */
intq_init (&txq);
mode = POLL;
}
/* Initializes the serial port device for queued interrupt-driven
I/O. With interrupt-driven I/O we don't waste CPU time
waiting for the serial device to become ready. */
void
serial_init_queue (void)
{
enum intr_level old_level;
if (mode == UNINIT)
init_poll ();
ASSERT (mode == POLL);
intr_register_ext (0x20 + 4, serial_interrupt, "serial");
mode = QUEUE;
old_level = intr_disable ();
write_ier ();
intr_set_level (old_level);
}
/* Sends BYTE to the serial port. */
void
serial_putc (uint8_t byte)
{
enum intr_level old_level = intr_disable ();
if (mode != QUEUE)
{
/* If we're not set up for interrupt-driven I/O yet,
use dumb polling to transmit a byte. */
if (mode == UNINIT)
init_poll ();
putc_poll (byte);
}
else
{
/* Otherwise, queue a byte and update the interrupt enable
register. */
if (old_level == INTR_OFF && intq_full (&txq))
{
/* Interrupts are off and the transmit queue is full.
If we wanted to wait for the queue to empty,
we'd have to reenable interrupts.
That's impolite, so we'll send a character via
polling instead. */
putc_poll (intq_getc (&txq));
}
intq_putc (&txq, byte);
write_ier ();
}
intr_set_level (old_level);
}
/* Flushes anything in the serial buffer out the port in polling
mode. */
void
serial_flush (void)
{
enum intr_level old_level = intr_disable ();
while (!intq_empty (&txq))
putc_poll (intq_getc (&txq));
intr_set_level (old_level);
}
/* The fullness of the input buffer may have changed. Reassess
whether we should block receive interrupts.
Called by the input buffer routines when characters are added
to or removed from the buffer. */
void
serial_notify (void)
{
ASSERT (intr_get_level () == INTR_OFF);
if (mode == QUEUE)
write_ier ();
}
/* Configures the serial port for BPS bits per second. */
static void
set_serial (int bps)
{
int base_rate = 1843200 / 16; /* Base rate of 16550A, in Hz. */
uint16_t divisor = base_rate / bps; /* Clock rate divisor. */
ASSERT (bps >= 300 && bps <= 115200);
/* Enable DLAB. */
outb (LCR_REG, LCR_N81 | LCR_DLAB);
/* Set data rate. */
outb (LS_REG, divisor & 0xff);
outb (MS_REG, divisor >> 8);
/* Reset DLAB. */
outb (LCR_REG, LCR_N81);
}
/* Update interrupt enable register. */
static void
write_ier (void)
{
uint8_t ier = 0;
ASSERT (intr_get_level () == INTR_OFF);
/* Enable transmit interrupt if we have any characters to
transmit. */
if (!intq_empty (&txq))
ier |= IER_XMIT;
/* Enable receive interrupt if we have room to store any
characters we receive. */
if (!input_full ())
ier |= IER_RECV;
outb (IER_REG, ier);
}
/* Polls the serial port until it's ready,
and then transmits BYTE. */
static void
putc_poll (uint8_t byte)
{
ASSERT (intr_get_level () == INTR_OFF);
while ((inb (LSR_REG) & LSR_THRE) == 0)
continue;
outb (THR_REG, byte);
}
/* Serial interrupt handler. */
static void
serial_interrupt (struct intr_frame *f UNUSED)
{
/* Inquire about interrupt in UART. Without this, we can
occasionally miss an interrupt running under QEMU. */
inb (IIR_REG);
/* As long as we have room to receive a byte, and the hardware
has a byte for us, receive a byte. */
while (!input_full () && (inb (LSR_REG) & LSR_DR) != 0)
input_putc (inb (RBR_REG));
/* As long as we have a byte to transmit, and the hardware is
ready to accept a byte for transmission, transmit a byte. */
while (!intq_empty (&txq) && (inb (LSR_REG) & LSR_THRE) != 0)
outb (THR_REG, intq_getc (&txq));
/* Update interrupt enable register based on queue status. */
write_ier ();
}
| 10cm | trunk/10cm/pintos/src/devices/serial.c | C | oos | 6,559 |
#include "devices/intq.h"
#include <debug.h>
#include "threads/thread.h"
static int next (int pos);
static void wait (struct intq *q, struct thread **waiter);
static void signal (struct intq *q, struct thread **waiter);
/* Initializes interrupt queue Q. */
void
intq_init (struct intq *q)
{
lock_init (&q->lock);
q->not_full = q->not_empty = NULL;
q->head = q->tail = 0;
}
/* Returns true if Q is empty, false otherwise. */
bool
intq_empty (const struct intq *q)
{
ASSERT (intr_get_level () == INTR_OFF);
return q->head == q->tail;
}
/* Returns true if Q is full, false otherwise. */
bool
intq_full (const struct intq *q)
{
ASSERT (intr_get_level () == INTR_OFF);
return next (q->head) == q->tail;
}
/* Removes a byte from Q and returns it.
If Q is empty, sleeps until a byte is added.
When called from an interrupt handler, Q must not be empty. */
uint8_t
intq_getc (struct intq *q)
{
uint8_t byte;
ASSERT (intr_get_level () == INTR_OFF);
while (intq_empty (q))
{
ASSERT (!intr_context ());
lock_acquire (&q->lock);
wait (q, &q->not_empty);
lock_release (&q->lock);
}
byte = q->buf[q->tail];
q->tail = next (q->tail);
signal (q, &q->not_full);
return byte;
}
/* Adds BYTE to the end of Q.
If Q is full, sleeps until a byte is removed.
When called from an interrupt handler, Q must not be full. */
void
intq_putc (struct intq *q, uint8_t byte)
{
ASSERT (intr_get_level () == INTR_OFF);
while (intq_full (q))
{
ASSERT (!intr_context ());
lock_acquire (&q->lock);
wait (q, &q->not_full);
lock_release (&q->lock);
}
q->buf[q->head] = byte;
q->head = next (q->head);
signal (q, &q->not_empty);
}
/* Returns the position after POS within an intq. */
static int
next (int pos)
{
return (pos + 1) % INTQ_BUFSIZE;
}
/* WAITER must be the address of Q's not_empty or not_full
member. Waits until the given condition is true. */
static void
wait (struct intq *q UNUSED, struct thread **waiter)
{
ASSERT (!intr_context ());
ASSERT (intr_get_level () == INTR_OFF);
ASSERT ((waiter == &q->not_empty && intq_empty (q))
|| (waiter == &q->not_full && intq_full (q)));
*waiter = thread_current ();
thread_block ();
}
/* WAITER must be the address of Q's not_empty or not_full
member, and the associated condition must be true. If a
thread is waiting for the condition, wakes it up and resets
the waiting thread. */
static void
signal (struct intq *q UNUSED, struct thread **waiter)
{
ASSERT (intr_get_level () == INTR_OFF);
ASSERT ((waiter == &q->not_empty && !intq_empty (q))
|| (waiter == &q->not_full && !intq_full (q)));
if (*waiter != NULL)
{
thread_unblock (*waiter);
*waiter = NULL;
}
}
| 10cm | trunk/10cm/pintos/src/devices/intq.c | C | oos | 2,792 |
#include "devices/timer.h"
#include <debug.h>
#include <inttypes.h>
#include <round.h>
#include <stdio.h>
#include "threads/interrupt.h"
#include "threads/io.h"
#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;
/* Number of loops per timer tick.
Initialized by timer_calibrate(). */
static unsigned loops_per_tick;
static intr_handler_func timer_interrupt;
static bool too_many_loops (unsigned loops);
static void busy_wait (int64_t loops);
static void real_time_sleep (int64_t num, int32_t denom);
static void real_time_delay (int64_t num, int32_t denom);
/* Sets up the 8254 Programmable Interval Timer (PIT) to
interrupt PIT_FREQ times per second, and registers the
corresponding interrupt. */
void
timer_init (void)
{
/* 8254 input frequency divided by TIMER_FREQ, rounded to
nearest. */
uint16_t count = (1193180 + TIMER_FREQ / 2) / TIMER_FREQ;
outb (0x43, 0x34); /* CW: counter 0, LSB then MSB, mode 2, binary. */
outb (0x40, count & 0xff);
outb (0x40, count >> 8);
intr_register_ext (0x20, timer_interrupt, "8254 Timer");
}
/* Calibrates loops_per_tick, used to implement brief delays. */
void
timer_calibrate (void)
{
unsigned high_bit, test_bit;
ASSERT (intr_get_level () == INTR_ON);
printf ("Calibrating timer... ");
/* Approximate loops_per_tick as the largest power-of-two
still less than 1 timer tick. */
loops_per_tick = 1u << 10;
while (!too_many_loops (loops_per_tick << 1))
{
loops_per_tick <<= 1;
ASSERT (loops_per_tick != 0);
}
/* Refine the next 8 bits of loops_per_tick. */
high_bit = loops_per_tick;
for (test_bit = high_bit >> 1; test_bit != high_bit >> 10; test_bit >>= 1)
if (!too_many_loops (high_bit | test_bit))
loops_per_tick |= test_bit;
printf ("%'"PRIu64" loops/s.\n", (uint64_t) loops_per_tick * TIMER_FREQ);
}
/* Returns the number of timer ticks since the OS booted. */
int64_t
timer_ticks (void)
{
enum intr_level old_level = intr_disable ();
int64_t t = ticks;
intr_set_level (old_level);
barrier ();
return t;
}
/* Returns the number of timer ticks elapsed since THEN, which
should be a value once returned by timer_ticks(). */
int64_t
timer_elapsed (int64_t then)
{
return timer_ticks () - then;
}
/* Sleeps for approximately TICKS timer ticks. Interrupts must
be turned on. */
void
timer_sleep (int64_t ticks)
{
int64_t start = timer_ticks ();
ASSERT (intr_get_level () == INTR_ON);
/* busy wait */
// while (timer_elapsed (start) < ticks)
// thread_yield ();
/* my new version */
add_block_list(start,ticks);
}
/* Sleeps for approximately MS milliseconds. Interrupts must be
turned on. */
void
timer_msleep (int64_t ms)
{
real_time_sleep (ms, 1000);
}
/* Sleeps for approximately US microseconds. Interrupts must be
turned on. */
void
timer_usleep (int64_t us)
{
real_time_sleep (us, 1000 * 1000);
}
/* Sleeps for approximately NS nanoseconds. Interrupts must be
turned on. */
void
timer_nsleep (int64_t ns)
{
real_time_sleep (ns, 1000 * 1000 * 1000);
}
/* Busy-waits for approximately MS milliseconds. Interrupts need
not be turned on.
Busy waiting wastes CPU cycles, and busy waiting with
interrupts off for the interval between timer ticks or longer
will cause timer ticks to be lost. Thus use timer_msleep()
instead if interrupts are enabled. */
void
timer_mdelay (int64_t ms)
{
real_time_delay (ms, 1000);
}
/* Sleeps for approximately US microseconds. Interrupts need not
be turned on.
Busy waiting wastes CPU cycles, and busy waiting with
interrupts off for the interval between timer ticks or longer
will cause timer ticks to be lost. Thus, use timer_usleep()
instead if interrupts are enabled. */
void
timer_udelay (int64_t us)
{
real_time_delay (us, 1000 * 1000);
}
/* Sleeps execution for approximately NS nanoseconds. Interrupts
need not be turned on.
Busy waiting wastes CPU cycles, and busy waiting with
interrupts off for the interval between timer ticks or longer
will cause timer ticks to be lost. Thus, use timer_nsleep()
instead if interrupts are enabled.*/
void
timer_ndelay (int64_t ns)
{
real_time_delay (ns, 1000 * 1000 * 1000);
}
/* Prints timer statistics. */
void
timer_print_stats (void)
{
printf ("Timer: %"PRId64" ticks\n", timer_ticks ());
}
/* Timer interrupt handler. */
static void
timer_interrupt (struct intr_frame *args UNUSED)
{
ticks++;
thread_tick ();
}
/* Returns true if LOOPS iterations waits for more than one timer
tick, otherwise false. */
static bool
too_many_loops (unsigned loops)
{
/* Wait for a timer tick. */
int64_t start = ticks;
while (ticks == start)
barrier ();
/* Run LOOPS loops. */
start = ticks;
busy_wait (loops);
/* If the tick count changed, we iterated too long. */
barrier ();
return start != ticks;
}
/* Iterates through a simple loop LOOPS times, for implementing
brief delays.
Marked NO_INLINE, because code alignment can significantly
affect timings, so that if this function was inlined
differently in different places the results would be difficult
to predict. */
static void NO_INLINE
busy_wait (int64_t loops)
{
while (loops-- > 0)
barrier ();
}
/* Sleep for approximately NUM/DENOM seconds. */
static void
real_time_sleep (int64_t num, int32_t denom)
{
/* Convert NUM/DENOM seconds into timer ticks, rounding down.
(NUM / DENOM) s
---------------------- = NUM * TIMER_FREQ / DENOM ticks.
1 s / TIMER_FREQ ticks
*/
int64_t ticks = num * TIMER_FREQ / denom;
ASSERT (intr_get_level () == INTR_ON);
if (ticks > 0)
{
/* We're waiting for at least one full timer tick. Use
timer_sleep() because it will yield the CPU to other
processes. */
timer_sleep (ticks);
}
else
{
/* Otherwise, use a busy-wait loop for more accurate
sub-tick timing. */
real_time_delay (num, denom);
}
}
/* Busy-wait for approximately NUM/DENOM seconds. */
static void
real_time_delay (int64_t num, int32_t denom)
{
/* Scale the numerator and denominator down by 1000 to avoid
the possibility of overflow. */
ASSERT (denom % 1000 == 0);
busy_wait (loops_per_tick * num / 1000 * TIMER_FREQ / (denom / 1000));
}
| 10cm | trunk/10cm/pintos/src/devices/timer.c | C | oos | 6,614 |
#include "devices/disk.h"
#include <ctype.h>
#include <debug.h>
#include <stdbool.h>
#include <stdio.h>
#include "devices/timer.h"
#include "threads/io.h"
#include "threads/interrupt.h"
#include "threads/synch.h"
/* The code in this file is an interface to an ATA (IDE)
controller. It attempts to comply to [ATA-3]. */
/* ATA command block port addresses. */
#define reg_data(CHANNEL) ((CHANNEL)->reg_base + 0) /* Data. */
#define reg_error(CHANNEL) ((CHANNEL)->reg_base + 1) /* Error. */
#define reg_nsect(CHANNEL) ((CHANNEL)->reg_base + 2) /* Sector Count. */
#define reg_lbal(CHANNEL) ((CHANNEL)->reg_base + 3) /* LBA 0:7. */
#define reg_lbam(CHANNEL) ((CHANNEL)->reg_base + 4) /* LBA 15:8. */
#define reg_lbah(CHANNEL) ((CHANNEL)->reg_base + 5) /* LBA 23:16. */
#define reg_device(CHANNEL) ((CHANNEL)->reg_base + 6) /* Device/LBA 27:24. */
#define reg_status(CHANNEL) ((CHANNEL)->reg_base + 7) /* Status (r/o). */
#define reg_command(CHANNEL) reg_status (CHANNEL) /* Command (w/o). */
/* ATA control block port addresses.
(If we supported non-legacy ATA controllers this would not be
flexible enough, but it's fine for what we do.) */
#define reg_ctl(CHANNEL) ((CHANNEL)->reg_base + 0x206) /* Control (w/o). */
#define reg_alt_status(CHANNEL) reg_ctl (CHANNEL) /* Alt Status (r/o). */
/* Alternate Status Register bits. */
#define STA_BSY 0x80 /* Busy. */
#define STA_DRDY 0x40 /* Device Ready. */
#define STA_DRQ 0x08 /* Data Request. */
/* Control Register bits. */
#define CTL_SRST 0x04 /* Software Reset. */
/* Device Register bits. */
#define DEV_MBS 0xa0 /* Must be set. */
#define DEV_LBA 0x40 /* Linear based addressing. */
#define DEV_DEV 0x10 /* Select device: 0=master, 1=slave. */
/* Commands.
Many more are defined but this is the small subset that we
use. */
#define CMD_IDENTIFY_DEVICE 0xec /* IDENTIFY DEVICE. */
#define CMD_READ_SECTOR_RETRY 0x20 /* READ SECTOR with retries. */
#define CMD_WRITE_SECTOR_RETRY 0x30 /* WRITE SECTOR with retries. */
/* An ATA device. */
struct disk
{
char name[8]; /* Name, e.g. "hd0:1". */
struct channel *channel; /* Channel disk is on. */
int dev_no; /* Device 0 or 1 for master or slave. */
bool is_ata; /* 1=This device is an ATA disk. */
disk_sector_t capacity; /* Capacity in sectors (if is_ata). */
long long read_cnt; /* Number of sectors read. */
long long write_cnt; /* Number of sectors written. */
};
/* An ATA channel (aka controller).
Each channel can control up to two disks. */
struct channel
{
char name[8]; /* Name, e.g. "hd0". */
uint16_t reg_base; /* Base I/O port. */
uint8_t irq; /* Interrupt in use. */
struct lock lock; /* Must acquire to access the controller. */
bool expecting_interrupt; /* True if an interrupt is expected, false if
any interrupt would be spurious. */
struct semaphore completion_wait; /* Up'd by interrupt handler. */
struct disk devices[2]; /* The devices on this channel. */
};
/* We support the two "legacy" ATA channels found in a standard PC. */
#define CHANNEL_CNT 2
static struct channel channels[CHANNEL_CNT];
static void reset_channel (struct channel *);
static bool check_device_type (struct disk *);
static void identify_ata_device (struct disk *);
static void select_sector (struct disk *, disk_sector_t);
static void issue_pio_command (struct channel *, uint8_t command);
static void input_sector (struct channel *, void *);
static void output_sector (struct channel *, const void *);
static void wait_until_idle (const struct disk *);
static bool wait_while_busy (const struct disk *);
static void select_device (const struct disk *);
static void select_device_wait (const struct disk *);
static void interrupt_handler (struct intr_frame *);
/* Initialize the disk subsystem and detect disks. */
void
disk_init (void)
{
size_t chan_no;
for (chan_no = 0; chan_no < CHANNEL_CNT; chan_no++)
{
struct channel *c = &channels[chan_no];
int dev_no;
/* Initialize channel. */
snprintf (c->name, sizeof c->name, "hd%zu", chan_no);
switch (chan_no)
{
case 0:
c->reg_base = 0x1f0;
c->irq = 14 + 0x20;
break;
case 1:
c->reg_base = 0x170;
c->irq = 15 + 0x20;
break;
default:
NOT_REACHED ();
}
lock_init (&c->lock);
c->expecting_interrupt = false;
sema_init (&c->completion_wait, 0);
/* Initialize devices. */
for (dev_no = 0; dev_no < 2; dev_no++)
{
struct disk *d = &c->devices[dev_no];
snprintf (d->name, sizeof d->name, "%s:%d", c->name, dev_no);
d->channel = c;
d->dev_no = dev_no;
d->is_ata = false;
d->capacity = 0;
d->read_cnt = d->write_cnt = 0;
}
/* Register interrupt handler. */
intr_register_ext (c->irq, interrupt_handler, c->name);
/* Reset hardware. */
reset_channel (c);
/* Distinguish ATA hard disks from other devices. */
if (check_device_type (&c->devices[0]))
check_device_type (&c->devices[1]);
/* Read hard disk identity information. */
for (dev_no = 0; dev_no < 2; dev_no++)
if (c->devices[dev_no].is_ata)
identify_ata_device (&c->devices[dev_no]);
}
}
/* Prints disk statistics. */
void
disk_print_stats (void)
{
int chan_no;
for (chan_no = 0; chan_no < CHANNEL_CNT; chan_no++)
{
int dev_no;
for (dev_no = 0; dev_no < 2; dev_no++)
{
struct disk *d = disk_get (chan_no, dev_no);
if (d != NULL && d->is_ata)
printf ("%s: %lld reads, %lld writes\n",
d->name, d->read_cnt, d->write_cnt);
}
}
}
/* Returns the disk numbered DEV_NO--either 0 or 1 for master or
slave, respectively--within the channel numbered CHAN_NO.
Pintos uses disks this way:
0:0 - boot loader, command line args, and operating system kernel
0:1 - file system
1:0 - scratch
1:1 - swap
*/
struct disk *
disk_get (int chan_no, int dev_no)
{
ASSERT (dev_no == 0 || dev_no == 1);
if (chan_no < (int) CHANNEL_CNT)
{
struct disk *d = &channels[chan_no].devices[dev_no];
if (d->is_ata)
return d;
}
return NULL;
}
/* Returns the size of disk D, measured in DISK_SECTOR_SIZE-byte
sectors. */
disk_sector_t
disk_size (struct disk *d)
{
ASSERT (d != NULL);
return d->capacity;
}
/* Reads sector SEC_NO from disk D into BUFFER, which must have
room for DISK_SECTOR_SIZE bytes.
Internally synchronizes accesses to disks, so external
per-disk locking is unneeded. */
void
disk_read (struct disk *d, disk_sector_t sec_no, void *buffer)
{
struct channel *c;
ASSERT (d != NULL);
ASSERT (buffer != NULL);
c = d->channel;
lock_acquire (&c->lock);
select_sector (d, sec_no);
issue_pio_command (c, CMD_READ_SECTOR_RETRY);
sema_down (&c->completion_wait);
if (!wait_while_busy (d))
PANIC ("%s: disk read failed, sector=%"PRDSNu, d->name, sec_no);
input_sector (c, buffer);
d->read_cnt++;
lock_release (&c->lock);
}
/* Write sector SEC_NO to disk D from BUFFER, which must contain
DISK_SECTOR_SIZE bytes. Returns after the disk has
acknowledged receiving the data.
Internally synchronizes accesses to disks, so external
per-disk locking is unneeded. */
void
disk_write (struct disk *d, disk_sector_t sec_no, const void *buffer)
{
struct channel *c;
ASSERT (d != NULL);
ASSERT (buffer != NULL);
c = d->channel;
lock_acquire (&c->lock);
select_sector (d, sec_no);
issue_pio_command (c, CMD_WRITE_SECTOR_RETRY);
if (!wait_while_busy (d))
PANIC ("%s: disk write failed, sector=%"PRDSNu, d->name, sec_no);
output_sector (c, buffer);
sema_down (&c->completion_wait);
d->write_cnt++;
lock_release (&c->lock);
}
/* Disk detection and identification. */
static void print_ata_string (char *string, size_t size);
/* Resets an ATA channel and waits for any devices present on it
to finish the reset. */
static void
reset_channel (struct channel *c)
{
bool present[2];
int dev_no;
/* The ATA reset sequence depends on which devices are present,
so we start by detecting device presence. */
for (dev_no = 0; dev_no < 2; dev_no++)
{
struct disk *d = &c->devices[dev_no];
select_device (d);
outb (reg_nsect (c), 0x55);
outb (reg_lbal (c), 0xaa);
outb (reg_nsect (c), 0xaa);
outb (reg_lbal (c), 0x55);
outb (reg_nsect (c), 0x55);
outb (reg_lbal (c), 0xaa);
present[dev_no] = (inb (reg_nsect (c)) == 0x55
&& inb (reg_lbal (c)) == 0xaa);
}
/* Issue soft reset sequence, which selects device 0 as a side effect.
Also enable interrupts. */
outb (reg_ctl (c), 0);
timer_usleep (10);
outb (reg_ctl (c), CTL_SRST);
timer_usleep (10);
outb (reg_ctl (c), 0);
timer_msleep (150);
/* Wait for device 0 to clear BSY. */
if (present[0])
{
select_device (&c->devices[0]);
wait_while_busy (&c->devices[0]);
}
/* Wait for device 1 to clear BSY. */
if (present[1])
{
int i;
select_device (&c->devices[1]);
for (i = 0; i < 3000; i++)
{
if (inb (reg_nsect (c)) == 1 && inb (reg_lbal (c)) == 1)
break;
timer_msleep (10);
}
wait_while_busy (&c->devices[1]);
}
}
/* Checks whether device D is an ATA disk and sets D's is_ata
member appropriately. If D is device 0 (master), returns true
if it's possible that a slave (device 1) exists on this
channel. If D is device 1 (slave), the return value is not
meaningful. */
static bool
check_device_type (struct disk *d)
{
struct channel *c = d->channel;
uint8_t error, lbam, lbah, status;
select_device (d);
error = inb (reg_error (c));
lbam = inb (reg_lbam (c));
lbah = inb (reg_lbah (c));
status = inb (reg_status (c));
if ((error != 1 && (error != 0x81 || d->dev_no == 1))
|| (status & STA_DRDY) == 0
|| (status & STA_BSY) != 0)
{
d->is_ata = false;
return error != 0x81;
}
else
{
d->is_ata = (lbam == 0 && lbah == 0) || (lbam == 0x3c && lbah == 0xc3);
return true;
}
}
/* Sends an IDENTIFY DEVICE command to disk D and reads the
response. Initializes D's capacity member based on the result
and prints a message describing the disk to the console. */
static void
identify_ata_device (struct disk *d)
{
struct channel *c = d->channel;
uint16_t id[DISK_SECTOR_SIZE / 2];
ASSERT (d->is_ata);
/* Send the IDENTIFY DEVICE command, wait for an interrupt
indicating the device's response is ready, and read the data
into our buffer. */
select_device_wait (d);
issue_pio_command (c, CMD_IDENTIFY_DEVICE);
sema_down (&c->completion_wait);
if (!wait_while_busy (d))
{
d->is_ata = false;
return;
}
input_sector (c, id);
/* Calculate capacity. */
d->capacity = id[60] | ((uint32_t) id[61] << 16);
/* Print identification message. */
printf ("%s: detected %'"PRDSNu" sector (", d->name, d->capacity);
if (d->capacity > 1024 / DISK_SECTOR_SIZE * 1024 * 1024)
printf ("%"PRDSNu" GB",
d->capacity / (1024 / DISK_SECTOR_SIZE * 1024 * 1024));
else if (d->capacity > 1024 / DISK_SECTOR_SIZE * 1024)
printf ("%"PRDSNu" MB", d->capacity / (1024 / DISK_SECTOR_SIZE * 1024));
else if (d->capacity > 1024 / DISK_SECTOR_SIZE)
printf ("%"PRDSNu" kB", d->capacity / (1024 / DISK_SECTOR_SIZE));
else
printf ("%"PRDSNu" byte", d->capacity * DISK_SECTOR_SIZE);
printf (") disk, model \"");
print_ata_string ((char *) &id[27], 40);
printf ("\", serial \"");
print_ata_string ((char *) &id[10], 20);
printf ("\"\n");
}
/* Prints STRING, which consists of SIZE bytes in a funky format:
each pair of bytes is in reverse order. Does not print
trailing whitespace and/or nulls. */
static void
print_ata_string (char *string, size_t size)
{
size_t i;
/* Find the last non-white, non-null character. */
for (; size > 0; size--)
{
int c = string[(size - 1) ^ 1];
if (c != '\0' && !isspace (c))
break;
}
/* Print. */
for (i = 0; i < size; i++)
printf ("%c", string[i ^ 1]);
}
/* Selects device D, waiting for it to become ready, and then
writes SEC_NO to the disk's sector selection registers. (We
use LBA mode.) */
static void
select_sector (struct disk *d, disk_sector_t sec_no)
{
struct channel *c = d->channel;
ASSERT (sec_no < d->capacity);
ASSERT (sec_no < (1UL << 28));
select_device_wait (d);
outb (reg_nsect (c), 1);
outb (reg_lbal (c), sec_no);
outb (reg_lbam (c), sec_no >> 8);
outb (reg_lbah (c), (sec_no >> 16));
outb (reg_device (c),
DEV_MBS | DEV_LBA | (d->dev_no == 1 ? DEV_DEV : 0) | (sec_no >> 24));
}
/* Writes COMMAND to channel C and prepares for receiving a
completion interrupt. */
static void
issue_pio_command (struct channel *c, uint8_t command)
{
/* Interrupts must be enabled or our semaphore will never be
up'd by the completion handler. */
ASSERT (intr_get_level () == INTR_ON);
c->expecting_interrupt = true;
outb (reg_command (c), command);
}
/* Reads a sector from channel C's data register in PIO mode into
SECTOR, which must have room for DISK_SECTOR_SIZE bytes. */
static void
input_sector (struct channel *c, void *sector)
{
insw (reg_data (c), sector, DISK_SECTOR_SIZE / 2);
}
/* Writes SECTOR to channel C's data register in PIO mode.
SECTOR must contain DISK_SECTOR_SIZE bytes. */
static void
output_sector (struct channel *c, const void *sector)
{
outsw (reg_data (c), sector, DISK_SECTOR_SIZE / 2);
}
/* Low-level ATA primitives. */
/* Wait up to 10 seconds for the controller to become idle, that
is, for the BSY and DRQ bits to clear in the status register.
As a side effect, reading the status register clears any
pending interrupt. */
static void
wait_until_idle (const struct disk *d)
{
int i;
for (i = 0; i < 1000; i++)
{
if ((inb (reg_status (d->channel)) & (STA_BSY | STA_DRQ)) == 0)
return;
timer_usleep (10);
}
printf ("%s: idle timeout\n", d->name);
}
/* Wait up to 30 seconds for disk D to clear BSY,
and then return the status of the DRQ bit.
The ATA standards say that a disk may take as long as that to
complete its reset. */
static bool
wait_while_busy (const struct disk *d)
{
struct channel *c = d->channel;
int i;
for (i = 0; i < 3000; i++)
{
if (i == 700)
printf ("%s: busy, waiting...", d->name);
if (!(inb (reg_alt_status (c)) & STA_BSY))
{
if (i >= 700)
printf ("ok\n");
return (inb (reg_alt_status (c)) & STA_DRQ) != 0;
}
timer_msleep (10);
}
printf ("failed\n");
return false;
}
/* Program D's channel so that D is now the selected disk. */
static void
select_device (const struct disk *d)
{
struct channel *c = d->channel;
uint8_t dev = DEV_MBS;
if (d->dev_no == 1)
dev |= DEV_DEV;
outb (reg_device (c), dev);
inb (reg_alt_status (c));
timer_nsleep (400);
}
/* Select disk D in its channel, as select_device(), but wait for
the channel to become idle before and after. */
static void
select_device_wait (const struct disk *d)
{
wait_until_idle (d);
select_device (d);
wait_until_idle (d);
}
/* ATA interrupt handler. */
static void
interrupt_handler (struct intr_frame *f)
{
struct channel *c;
for (c = channels; c < channels + CHANNEL_CNT; c++)
if (f->vec_no == c->irq)
{
if (c->expecting_interrupt)
{
inb (reg_status (c)); /* Acknowledge interrupt. */
sema_up (&c->completion_wait); /* Wake up waiter. */
}
else
printf ("%s: unexpected interrupt\n", c->name);
return;
}
NOT_REACHED ();
}
| 10cm | trunk/10cm/pintos/src/devices/disk.c | C | oos | 16,321 |
#ifndef DEVICES_INTQ_H
#define DEVICES_INTQ_H
#include "threads/interrupt.h"
#include "threads/synch.h"
/* An "interrupt queue", a circular buffer shared between
kernel threads and external interrupt handlers.
Interrupt queue functions can be called from kernel threads or
from external interrupt handlers. Except for intq_init(),
interrupts must be off in either case.
The interrupt queue has the structure of a "monitor". Locks
and condition variables from threads/synch.h cannot be used in
this case, as they normally would, because they can only
protect kernel threads from one another, not from interrupt
handlers. */
/* Queue buffer size, in bytes. */
#define INTQ_BUFSIZE 64
/* A circular queue of bytes. */
struct intq
{
/* Waiting threads. */
struct lock lock; /* Only one thread may wait at once. */
struct thread *not_full; /* Thread waiting for not-full condition. */
struct thread *not_empty; /* Thread waiting for not-empty condition. */
/* Queue. */
uint8_t buf[INTQ_BUFSIZE]; /* Buffer. */
int head; /* New data is written here. */
int tail; /* Old data is read here. */
};
void intq_init (struct intq *);
bool intq_empty (const struct intq *);
bool intq_full (const struct intq *);
uint8_t intq_getc (struct intq *);
void intq_putc (struct intq *, uint8_t);
#endif /* devices/intq.h */
| 10cm | trunk/10cm/pintos/src/devices/intq.h | C | oos | 1,429 |
#ifndef DEVICES_INPUT_H
#define DEVICES_INPUT_H
#include <stdbool.h>
#include <stdint.h>
void input_init (void);
void input_putc (uint8_t);
uint8_t input_getc (void);
bool input_full (void);
#endif /* devices/input.h */
| 10cm | trunk/10cm/pintos/src/devices/input.h | C | oos | 223 |
#include "devices/rtc.h"
#include <stdio.h>
#include "threads/io.h"
/* This code is an interface to the MC146818A-compatible real
time clock found on PC motherboards. See [MC146818A] for
hardware details. */
/* I/O register addresses. */
#define CMOS_REG_SET 0x70 /* Selects CMOS register exposed by REG_IO. */
#define CMOS_REG_IO 0x71 /* Contains the selected data byte. */
/* Indexes of CMOS registers with real-time clock functions.
Note that all of these registers are in BCD format,
so that 0x59 means 59, not 89. */
#define RTC_REG_SEC 0 /* Second: 0x00...0x59. */
#define RTC_REG_MIN 2 /* Minute: 0x00...0x59. */
#define RTC_REG_HOUR 4 /* Hour: 0x00...0x23. */
#define RTC_REG_MDAY 7 /* Day of the month: 0x01...0x31. */
#define RTC_REG_MON 8 /* Month: 0x01...0x12. */
#define RTC_REG_YEAR 9 /* Year: 0x00...0x99. */
/* Indexes of CMOS control registers. */
#define RTC_REG_A 0x0a /* Register A: update-in-progress. */
#define RTC_REG_B 0x0b /* Register B: 24/12 hour time, irq enables. */
#define RTC_REG_C 0x0c /* Register C: pending interrupts. */
#define RTC_REG_D 0x0d /* Register D: valid time? */
/* Register A. */
#define RTCSA_UIP 0x80 /* Set while time update in progress. */
/* Register B. */
#define RTCSB_SET 0x80 /* Disables update to let time be set. */
#define RTCSB_DM 0x04 /* 0 = BCD time format, 1 = binary format. */
#define RTCSB_24HR 0x02 /* 0 = 12-hour format, 1 = 24-hour format. */
static int bcd_to_bin (uint8_t);
static uint8_t cmos_read (uint8_t index);
/* Returns number of seconds since Unix epoch of January 1,
1970. */
time_t
rtc_get_time (void)
{
static const int days_per_month[12] =
{
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
int sec, min, hour, mday, mon, year;
time_t time;
int i;
/* Get time components.
We repeatedly read the time until it is stable from one read
to another, in case we start our initial read in the middle
of an update. This strategy is not recommended by the
MC146818A datasheet, but it is simpler than any of their
suggestions and, furthermore, it is also used by Linux.
The MC146818A can be configured for BCD or binary format,
but for historical reasons everyone always uses BCD format
except on obscure non-PC platforms, so we don't bother
trying to detect the format in use. */
do
{
sec = bcd_to_bin (cmos_read (RTC_REG_SEC));
min = bcd_to_bin (cmos_read (RTC_REG_MIN));
hour = bcd_to_bin (cmos_read (RTC_REG_HOUR));
mday = bcd_to_bin (cmos_read (RTC_REG_MDAY));
mon = bcd_to_bin (cmos_read (RTC_REG_MON));
year = bcd_to_bin (cmos_read (RTC_REG_YEAR));
}
while (sec != bcd_to_bin (cmos_read (RTC_REG_SEC)));
/* Translate years-since-1900 into years-since-1970.
If it's before the epoch, assume that it has passed 2000.
This will break at 2070, but that's long after our 31-bit
time_t breaks in 2038. */
if (year < 70)
year += 100;
year -= 70;
/* Break down all components into seconds. */
time = (year * 365 + (year - 1) / 4) * 24 * 60 * 60;
for (i = 1; i <= mon; i++)
time += days_per_month[i - 1] * 24 * 60 * 60;
if (mon > 2 && year % 4 == 0)
time += 24 * 60 * 60;
time += (mday - 1) * 24 * 60 * 60;
time += hour * 60 * 60;
time += min * 60;
time += sec;
return time;
}
/* Returns the integer value of the given BCD byte. */
static int
bcd_to_bin (uint8_t x)
{
return (x & 0x0f) + ((x >> 4) * 10);
}
/* Reads a byte from the CMOS register with the given INDEX and
returns the byte read. */
static uint8_t
cmos_read (uint8_t index)
{
outb (CMOS_REG_SET, index);
return inb (CMOS_REG_IO);
}
| 10cm | trunk/10cm/pintos/src/devices/rtc.c | C | oos | 3,725 |
#include "devices/vga.h"
#include <round.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "threads/io.h"
#include "threads/interrupt.h"
#include "threads/vaddr.h"
/* VGA text screen support. See [FREEVGA] for more information. */
/* Number of columns and rows on the text display. */
#define COL_CNT 80
#define ROW_CNT 25
/* Current cursor position. (0,0) is in the upper left corner of
the display. */
static size_t cx, cy;
/* Attribute value for gray text on a black background. */
#define GRAY_ON_BLACK 0x07
/* Framebuffer. See [FREEVGA] under "VGA Text Mode Operation".
The character at (x,y) is fb[y][x][0].
The attribute at (x,y) is fb[y][x][1]. */
static uint8_t (*fb)[COL_CNT][2];
static void clear_row (size_t y);
static void cls (void);
static void newline (void);
static void move_cursor (void);
static void find_cursor (size_t *x, size_t *y);
/* Initializes the VGA text display. */
static void
init (void)
{
/* Already initialized? */
static bool inited;
if (!inited)
{
fb = ptov (0xb8000);
find_cursor (&cx, &cy);
inited = true;
}
}
/* Writes C to the VGA text display, interpreting control
characters in the conventional ways. */
void
vga_putc (int c)
{
/* Disable interrupts to lock out interrupt handlers
that might write to the console. */
enum intr_level old_level = intr_disable ();
init ();
switch (c)
{
case '\n':
newline ();
break;
case '\f':
cls ();
break;
case '\b':
if (cx > 0)
cx--;
break;
case '\r':
cx = 0;
break;
case '\t':
cx = ROUND_UP (cx + 1, 8);
if (cx >= COL_CNT)
newline ();
break;
default:
fb[cy][cx][0] = c;
fb[cy][cx][1] = GRAY_ON_BLACK;
if (++cx >= COL_CNT)
newline ();
break;
}
/* Update cursor position. */
move_cursor ();
intr_set_level (old_level);
}
/* Clears the screen and moves the cursor to the upper left. */
static void
cls (void)
{
size_t y;
for (y = 0; y < ROW_CNT; y++)
clear_row (y);
cx = cy = 0;
move_cursor ();
}
/* Clears row Y to spaces. */
static void
clear_row (size_t y)
{
size_t x;
for (x = 0; x < COL_CNT; x++)
{
fb[y][x][0] = ' ';
fb[y][x][1] = GRAY_ON_BLACK;
}
}
/* Advances the cursor to the first column in the next line on
the screen. If the cursor is already on the last line on the
screen, scrolls the screen upward one line. */
static void
newline (void)
{
cx = 0;
cy++;
if (cy >= ROW_CNT)
{
cy = ROW_CNT - 1;
memmove (&fb[0], &fb[1], sizeof fb[0] * (ROW_CNT - 1));
clear_row (ROW_CNT - 1);
}
}
/* Moves the hardware cursor to (cx,cy). */
static void
move_cursor (void)
{
/* See [FREEVGA] under "Manipulating the Text-mode Cursor". */
uint16_t cp = cx + COL_CNT * cy;
outw (0x3d4, 0x0e | (cp & 0xff00));
outw (0x3d4, 0x0f | (cp << 8));
}
/* Reads the current hardware cursor position into (*X,*Y). */
static void
find_cursor (size_t *x, size_t *y)
{
/* See [FREEVGA] under "Manipulating the Text-mode Cursor". */
uint16_t cp;
outb (0x3d4, 0x0e);
cp = inb (0x3d5) << 8;
outb (0x3d4, 0x0f);
cp |= inb (0x3d5);
*x = cp % COL_CNT;
*y = cp / COL_CNT;
}
| 10cm | trunk/10cm/pintos/src/devices/vga.c | C | oos | 3,304 |
#ifndef DEVICES_VGA_H
#define DEVICES_VGA_H
void vga_putc (int);
#endif /* devices/vga.h */
| 10cm | trunk/10cm/pintos/src/devices/vga.h | C | oos | 94 |
#ifndef DEVICES_SERIAL_H
#define DEVICES_SERIAL_H
#include <stdint.h>
void serial_init_queue (void);
void serial_putc (uint8_t);
void serial_flush (void);
void serial_notify (void);
#endif /* devices/serial.h */
| 10cm | trunk/10cm/pintos/src/devices/serial.h | C | oos | 215 |
#include "userprog/exception.h"
#include <inttypes.h>
#include <stdio.h>
#include "userprog/gdt.h"
#include "userprog/process.h"
#include "threads/interrupt.h"
#include "threads/thread.h"
#include "threads/palloc.h"
#include "threads/vaddr.h"
#include "vm/frame.h"
#include "vm/swap.h"
/* Number of page faults that are processed. */
static long long page_fault_cnt;
static void kill (struct intr_frame *);
static void page_fault (struct intr_frame *);
static void exception_process_kill(void);
static bool is_stack_bound_addr(void* fault_addr, void* esp, bool user);
/* Registers handlers for interrupts that can be caused by user
programs.
In a real Unix-like OS, most of these interrupts would be
passed along to the user process in the form of signals, as
described in [SV-386] 3-24 and 3-25, but we don't implement
signals. Instead, we'll make them simply kill the user
process.
Page faults are an exception. Here they are treated the same
way as other exceptions, but this will need to change to
implement virtual memory.
Refer to [IA32-v3a] section 5.15 "Exception and Interrupt
Reference" for a description of each of these exceptions. */
void
exception_init (void)
{
/* These exceptions can be raised explicitly by a user program,
e.g. via the INT, INT3, INTO, and BOUND instructions. Thus,
we set DPL==3, meaning that user programs are allowed to
invoke them via these instructions. */
intr_register_int (3, 3, INTR_ON, kill, "#BP Breakpoint Exception");
intr_register_int (4, 3, INTR_ON, kill, "#OF Overflow Exception");
intr_register_int (5, 3, INTR_ON, kill,
"#BR BOUND Range Exceeded Exception");
/* These exceptions have DPL==0, preventing user processes from
invoking them via the INT instruction. They can still be
caused indirectly, e.g. #DE can be caused by dividing by
0. */
intr_register_int (0, 0, INTR_ON, kill, "#DE Divide Error");
intr_register_int (1, 0, INTR_ON, kill, "#DB Debug Exception");
intr_register_int (6, 0, INTR_ON, kill, "#UD Invalid Opcode Exception");
intr_register_int (7, 0, INTR_ON, kill,
"#NM Device Not Available Exception");
intr_register_int (11, 0, INTR_ON, kill, "#NP Segment Not Present");
intr_register_int (12, 0, INTR_ON, kill, "#SS Stack Fault Exception");
intr_register_int (13, 0, INTR_ON, kill, "#GP General Protection Exception");
intr_register_int (16, 0, INTR_ON, kill, "#MF x87 FPU Floating-Point Error");
intr_register_int (19, 0, INTR_ON, kill,
"#XF SIMD Floating-Point Exception");
/* Most exceptions can be handled with interrupts turned on.
We need to disable interrupts for page faults because the
fault address is stored in CR2 and needs to be preserved. */
intr_register_int (14, 0, INTR_OFF, page_fault, "#PF Page-Fault Exception");
}
/* Prints exception statistics. */
void
exception_print_stats (void)
{
printf ("Exception: %lld page faults\n", page_fault_cnt);
}
/* Handler for an exception (probably) caused by a user process. */
static void
kill (struct intr_frame *f)
{
/* This interrupt is one(probably) caused by a user process.
For example, the process might have tried to access unmapped
virtual memory (a page fault). For now, we simply kill the
user process. Later, we'll want to handle page faults in
the kernel. Real Unix-like operating systems pass most
exceptions back to the process via signals, but we don't
implement them. */
/* The interrupt frame's code segment value tells us where the
exception originated. */
switch (f->cs)
{
case SEL_UCSEG:
/* User's code segment, so it's a user exception, as we
expected. Kill the user process. */
printf ("%s: dying due to interrupt %#04x (%s).\n",
thread_name (), f->vec_no, intr_name (f->vec_no));
intr_dump_frame (f);
thread_exit ();
case SEL_KCSEG:
/* Kernel's code segment, which indicates a kernel bug.
Kernel code shouldn't throw exceptions. (Page faults
may cause kernel exceptions--but they shouldn't arrive
here.) Panic the kernel to make the point. */
intr_dump_frame (f);
PANIC ("Kernel bug - unexpected interrupt in kernel");
default:
/* Some other code segment? Shouldn't happen. Panic the
kernel. */
printf ("Interrupt %#04x (%s) in unknown segment %04x\n",
f->vec_no, intr_name (f->vec_no), f->cs);
thread_exit ();
}
}
/* Page fault handler. This is a skeleton that must be filled in
to implement virtual memory. Some solutions to project 2 may
also require modifying this code.
At entry, the address that faulted is in CR2 (Control Register
2) and information about the fault, formatted as described in
the PF_* macros in exception.h, is in F's error_code member. The
example code here shows how to parse that information. You
can find more information about both of these in the
description of "Interrupt 14--Page Fault Exception (#PF)" in
[IA32-v3a] section 5.15 - "Exception and Interrupt Reference". */
static void
page_fault (struct intr_frame *f)
{
bool not_present; /* True: not-present page, false: writing r/o page. */
bool write; /* True: access was write, false: access was read. */
bool user; /* True: access by user, false: access by kernel. */
void *fault_addr; /* Fault address. */
/* Obtain faulting address, the virtual address that was
accessed to cause the fault. It may point to code or to
data. It is not necessarily the address of the instruction
that caused the fault (that is f->eip).
See [IA32-v2a] "MOV--Move to/from Control Registers" and
[IA32-v3a] 5.15 "Interrupt 14--Page Fault Exception
(#PF)". */
asm ("movl %%cr2, %0" : "=r" (fault_addr));
/* Turn interrupts back on (they were only off so that we could
be assured of reading CR2 before it changed). */
intr_enable ();
/* Count page faults. */
page_fault_cnt++;
/* Determine cause. */
not_present = (f->error_code & PF_P) == 0;
write = (f->error_code & PF_W) != 0;
user = (f->error_code & PF_U) != 0;
// 일단 해당 페이지 테이블이 없어서 에러가 난 경우여야 하고(rights violation 제외)
// fault_addr이 user영역의 페이지에 대한 것일때에만 처리한다.
struct thread *t = thread_current();
if (not_present && is_user_vaddr(fault_addr)){
// 에러난 주소의 페이지 주소를 가져온다.
void* upage = pg_round_down(fault_addr);
// 이 페이지가 혹시 swap out 되어있는지 확인한다.
struct page* p = swap_get_page(thread_current(), upage);
if (p != NULL){
// swap out 된 페이지라면 다시 swap in 해서 올리도록 한다.
if (!frame_load(upage)){
printf("swap fail..\n");
exception_process_kill();
}
return;
}
// 그렇지 않은 경우 에러난 주소가 스택 영역 안의 주소가 맞는지 확인해
// 올바른 스택 범위 안의 주소이 새 페이지를 할당해준다. ( grow stack )
if (is_stack_bound_addr(fault_addr, f->esp, user)){
if (!frame_allocate_new(upage, true)){
printf("stack grow fail..\n");
exception_process_kill();
}
// stack 영역이 넓어졌으면 넓어진 영역범위를 thread의 low_esp 변수에 기록한다.
if (upage < t->low_esp) t->low_esp = upage;
return;
}
}
/* To implement virtual memory delete the rest of the function
body, and replace it with code that brings in the page to
which fault_addr refers. */
printf ("Page fault at %p: %s error %s page in %s context.\n",
fault_addr,
not_present ? "not present" : "rights violation",
write ? "writing" : "reading",
user ? "user" : "kernel");
exception_process_kill();
}
/* fault_addr이 올바른 스택 영역 안의 주소인지 확인하는 함수 */
static bool is_stack_bound_addr(void* fault_addr, void* esp, bool user){
if (user){
// user process에서의 에러인 경우
// esp가 user_addr 영역이어야 한다.
if (!is_user_vaddr(esp)) return false;
// fault_addr이 esp보다 크거나 같아야 한다. ( esp 위에 있어야 함 )
if (fault_addr < esp) return false;
} else {
// fault_addr이 현재까지 할당한 stack영역 위에 있어야 한다.
if (fault_addr < thread_current()->low_esp) return false;
}
return true;
}
static void exception_process_kill(void){
set_process_exited(-1);
thread_exit();
}
| 10cm | trunk/10cm/pintos/src/userprog/exception.c | C | oos | 8,621 |
#ifndef USERPROG_TSS_H
#define USERPROG_TSS_H
#include <stdint.h>
struct tss;
void tss_init (void);
struct tss *tss_get (void);
void tss_update (void);
#endif /* userprog/tss.h */
| 10cm | trunk/10cm/pintos/src/userprog/tss.h | C | oos | 183 |
#include "userprog/syscall.h"
#include "userprog/process.h"
#include "userprog/pagedir.h"
#include <stdio.h>
#include <syscall-nr.h>
#include "threads/interrupt.h"
#include "threads/thread.h"
#include "threads/malloc.h"
#include "threads/synch.h"
#include "filesys/filesys.h"
#include "filesys/file.h"
#include "devices/input.h"
#include "devices/timer.h"
#include "threads/vaddr.h"
/* This is a skeleton system call handler */
static void syscall_handler(struct intr_frame *);
bool syscall_create(uint32_t *esp);
bool syscall_remove(uint32_t *esp);
int syscall_open(uint32_t *esp);
void syscall_close(uint32_t *esp);
int syscall_write(uint32_t *esp);
int syscall_read(uint32_t *esp);
int syscall_filesize(uint32_t *esp);
int syscall_exec(uint32_t *esp);
int syscall_wait(uint32_t *esp);
void syscall_exit(uint32_t *esp);
void exit_direct(int status);
fd_element* find_fd_element(int fd);
void check_address_valid (void *addr);
struct lock file_lock;
void syscall_init(void) {
lock_init(&file_lock);
intr_register_int(0x30, 3, INTR_ON, syscall_handler, "syscall");
}
static void syscall_handler(struct intr_frame *f UNUSED) {
uint32_t *esp = f->esp;
int sys_num = (int) *(esp++);
if (SYS_CREATE == sys_num) {
f->eax = syscall_create(esp);
return;
} else if (SYS_OPEN == sys_num) {
f->eax = syscall_open(esp);
return;
} else if (SYS_REMOVE == sys_num) {
f->eax = syscall_remove(esp);
return;
} else if (SYS_CLOSE == sys_num) {
syscall_close(esp);
return;
} else if (SYS_WRITE == sys_num) {
f->eax = syscall_write(esp);
return;
} else if (SYS_READ == sys_num) {
f->eax = syscall_read(esp);
return;
} else if (SYS_FILESIZE == sys_num) {
f->eax = syscall_filesize(esp);
return;
} else if (SYS_EXEC == sys_num) {
f->eax = syscall_exec(esp);
return;
} else if (SYS_WAIT == sys_num) {
f->eax = syscall_wait(esp);
return;
} else if (SYS_EXIT == sys_num) {
syscall_exit(esp);
return;
} else if (SYS_TIMER == sys_num) {
int time = timer_ticks() % 1000000000;
f->eax = time;
return;
} else {
printf("other system call : sys_num(%d)\n", sys_num);
}
thread_exit();
}
bool syscall_create(uint32_t *esp) {
char *file_path = (char *) *(esp)++;
uint32_t size = (uint32_t) *(esp)++;
check_address_valid(file_path);
if (file_path == NULL) return false;
lock_acquire(&file_lock);
bool result = filesys_create(file_path, size);
lock_release(&file_lock);
return result;
}
bool syscall_remove(uint32_t *esp){
char *file_path = (char *) *(esp)++;
check_address_valid(file_path);
if (file_path == NULL) return false;
lock_acquire(&file_lock);
bool result = filesys_remove(file_path);
lock_release(&file_lock);
return result;
}
int syscall_open(uint32_t *esp) {
char* file_path = (char *) *(esp++);
check_address_valid(file_path);
if (file_path == NULL) return -1;
struct thread *t = thread_current();
struct list_elem *e;
int fd_num = 2;
fd_element *fd_elem;
for (e = list_begin(&t->fd_list); e != list_end(&t->fd_list); e
= list_next(e)) {
fd_elem = list_entry (e, fd_element, elem);
if (fd_elem->fd_number == fd_num) {
fd_num++;
} else {
break;
}
}
fd_elem = malloc(sizeof(fd_element));
fd_elem->fd_number = fd_num;
lock_acquire(&file_lock);
fd_elem->file = filesys_open(file_path);
lock_release(&file_lock);
if (fd_elem->file == NULL) {
free(fd_elem);
return -1;
} else {
list_insert(e, &fd_elem->elem);
return fd_num;
}
}
void syscall_close(uint32_t *esp) {
int fd = (int) *(esp)++;
fd_element* fd_elem = find_fd_element(fd);
if (fd_elem == NULL) return;
lock_acquire(&file_lock);
file_close(fd_elem->file);
lock_release(&file_lock);
list_remove(&fd_elem->elem);
free(fd_elem);
}
int syscall_write(uint32_t *esp) {
int fd = (int) *(esp++);
char* buffer = (char *) *(esp++);
unsigned size = (unsigned) *(esp++);
check_address_valid(buffer);
if (buffer == NULL) return -1;
if (fd == 1) {
// write to console
putbuf(buffer, size);
return size;
} else if (fd >= 2) {
fd_element* fd_elem = find_fd_element(fd);
if (fd_elem == NULL) return -1;
return file_write(fd_elem->file, buffer, size);
} else {
return -1;
}
}
int syscall_read(uint32_t *esp) {
int fd = (int) *(esp++);
char* buffer = (char *) *(esp++);
unsigned size = (unsigned) *(esp++);
check_address_valid(buffer);
if (buffer == NULL) return -1;
if (fd == 0) {
// read from console
unsigned i;
for (i = 0;i < size; i++){
buffer[i] = input_getc();
}
return size;
} else if (fd >= 2) {
fd_element* fd_elem = find_fd_element(fd);
if (fd_elem == NULL) return -1;
return file_read(fd_elem->file, buffer, size);
} else {
return -1;
}
}
int syscall_filesize(uint32_t *esp){
int fd = (int) *(esp++);
fd_element* fd_elem = find_fd_element(fd);
if (fd_elem == NULL) return -1;
return file_length(fd_elem->file);
}
fd_element* find_fd_element(int fd) {
struct thread *t = thread_current();
struct list_elem *e;
for (e = list_begin(&t->fd_list); e != list_end(&t->fd_list); e
= list_next(e)) {
fd_element *fd_elem = list_entry (e, fd_element, elem);
if (fd_elem->fd_number == fd) {
return fd_elem;
}
}
return NULL;
}
int syscall_exec(uint32_t *esp){
char *cmd_line = (char *)*(esp++);
check_address_valid(cmd_line);
tid_t tid = process_execute(cmd_line);
return tid;
}
int syscall_wait(uint32_t *esp){
tid_t tid = (tid_t) *(esp++);
return process_wait(tid);
}
void syscall_exit (uint32_t *esp) {
int status = (int) *(esp++);
exit_direct(status);
}
void exit_direct(int status){
set_process_exited(status);
thread_exit();
}
void check_address_valid (void *addr)
{
if (!is_user_vaddr(addr)){
printf("syscall error : invalid kernel address access\n");
exit_direct(-1);
}
}
| 10cm | trunk/10cm/pintos/src/userprog/syscall.c | C | oos | 5,739 |
#ifndef USERPROG_GDT_H
#define USERPROG_GDT_H
#include "threads/loader.h"
/* Segment selectors.
More selectors are defined by the loader in loader.h. */
#define SEL_UCSEG 0x1B /* User code selector. */
#define SEL_UDSEG 0x23 /* User data selector. */
#define SEL_TSS 0x28 /* Task-state segment. */
#define SEL_CNT 6 /* Number of segments. */
void gdt_init (void);
#endif /* userprog/gdt.h */
| 10cm | trunk/10cm/pintos/src/userprog/gdt.h | C | oos | 442 |
# -*- makefile -*-
os.dsk: DEFINES = -DUSERPROG -DFILESYS
KERNEL_SUBDIRS = threads devices lib lib/kernel userprog filesys
TEST_SUBDIRS = tests/userprog tests/userprog/no-vm tests/filesys/base
GRADING_FILE = $(SRCDIR)/tests/userprog/Grading
SIMULATOR = --qemu
| 10cm | trunk/10cm/pintos/src/userprog/Make.vars | Makefile | oos | 261 |
#include "userprog/tss.h"
#include <debug.h>
#include <stddef.h>
#include "userprog/gdt.h"
#include "threads/thread.h"
#include "threads/palloc.h"
#include "threads/vaddr.h"
/* The Task-State Segment (TSS).
Instances of the TSS, an x86-specific structure, are used to
define "tasks", a form of support for multitasking built right
into the processor. However, for various reasons including
portability, speed, and flexibility, most x86 OSes almost
completely ignore the TSS. We are no exception.
Unfortunately, there is one thing that can only be done using
a TSS: stack switching for interrupts that occur in user mode.
When an interrupt occurs in user mode (ring 3), the processor
consults the ss0 and esp0 members of the current TSS to
determine the stack to use for handling the interrupt. Thus,
we must create a TSS and initialize at least these fields, and
this is precisely what this file does.
When an interrupt is handled by an interrupt or trap gate
(which applies to all interrupts we handle), an x86 processor
works like this:
- If the code interrupted by the interrupt is in the same
ring as the interrupt handler, then no stack switch takes
place. This is the case for interrupts that happen when
we're running in the kernel. The contents of the TSS are
irrelevant for this case.
- If the interrupted code is in a different ring from the
handler, then the processor switches to the stack
specified in the TSS for the new ring. This is the case
for interrupts that happen when we're in user space. It's
important that we switch to a stack that's not already in
use, to avoid corruption. Because we're running in user
space, we know that the current process's kernel stack is
not in use, so we can always use that. Thus, when the
scheduler switches threads, it also changes the TSS's
stack pointer to point to the new thread's kernel stack.
(The call is in schedule_tail() in thread.c.)
See [IA32-v3a] 6.2.1 "Task-State Segment (TSS)" for a
description of the TSS. See [IA32-v3a] 5.12.1 "Exception- or
Interrupt-Handler Procedures" for a description of when and
how stack switching occurs during an interrupt. */
struct tss
{
uint16_t back_link, :16;
void *esp0; /* Ring 0 stack virtual address. */
uint16_t ss0, :16; /* Ring 0 stack segment selector. */
void *esp1;
uint16_t ss1, :16;
void *esp2;
uint16_t ss2, :16;
uint32_t cr3;
void (*eip) (void);
uint32_t eflags;
uint32_t eax, ecx, edx, ebx;
uint32_t esp, ebp, esi, edi;
uint16_t es, :16;
uint16_t cs, :16;
uint16_t ss, :16;
uint16_t ds, :16;
uint16_t fs, :16;
uint16_t gs, :16;
uint16_t ldt, :16;
uint16_t trace, bitmap;
};
/* Kernel TSS. */
static struct tss *tss;
/* Initializes the kernel TSS. */
void
tss_init (void)
{
/* Our TSS is never used in a call gate or task gate, so only a
few fields of it are ever referenced, and those are the only
ones we initialize. */
tss = palloc_get_page (PAL_ASSERT | PAL_ZERO);
tss->ss0 = SEL_KDSEG;
tss->bitmap = 0xdfff;
tss_update ();
}
/* Returns the kernel TSS. */
struct tss *
tss_get (void)
{
ASSERT (tss != NULL);
return tss;
}
/* Sets the ring 0 stack pointer in the TSS to point to the end
of the thread stack. */
void
tss_update (void)
{
ASSERT (tss != NULL);
tss->esp0 = (uint8_t *) thread_current () + PGSIZE;
}
| 10cm | trunk/10cm/pintos/src/userprog/tss.c | C | oos | 3,577 |
# -*- makefile -*-
os.dsk: DEFINES = -DUSERPROG -DFILESYS
KERNEL_SUBDIRS = threads devices lib lib/kernel userprog filesys
TEST_SUBDIRS = tests/userprog tests/userprog/no-vm tests/filesys/base
GRADING_FILE = $(SRCDIR)/tests/userprog/Grading
SIMULATOR = --qemu
| 10cm | trunk/10cm/pintos/src/userprog/.svn/text-base/Make.vars.svn-base | Makefile | oos | 261 |
#ifndef USERPROG_PROCESS_H
#define USERPROG_PROCESS_H
#include "threads/thread.h"
tid_t process_execute (const char *file_name);
int process_wait (tid_t);
void process_exit (void);
void process_activate (void);
void set_process_exited (int exit_status);
#endif /* userprog/process.h */
| 10cm | trunk/10cm/pintos/src/userprog/process.h | C | oos | 291 |
#include "userprog/process.h"
#include <debug.h>
#include <inttypes.h>
#include <round.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "userprog/gdt.h"
#include "userprog/pagedir.h"
#include "userprog/tss.h"
#include "filesys/directory.h"
#include "filesys/file.h"
#include "filesys/filesys.h"
#include "threads/flags.h"
#include "threads/init.h"
#include "threads/interrupt.h"
#include "threads/palloc.h"
#include "threads/thread.h"
#include "threads/vaddr.h"
#include "threads/malloc.h"
#include "vm/frame.h"
typedef struct _process {
tid_t tid;
tid_t parent_tid;
bool is_exited;
int exit_status;
struct list_elem elem;
} process;
typedef struct _waiting_process {
struct thread *t;
tid_t waiting_tid;
struct list_elem elem;
} waiting_process;
struct list process_list;
struct list waiting_list;
bool is_initialized = false;
int initial_thread_tid;
static thread_func start_process NO_RETURN;
static bool load (const char *cmdline, void (**eip) (void), void **esp);
/* Starts a new thread running a user program loaded from
FILENAME. The new thread may be scheduled (and may even exit)
before process_execute() returns. Returns the new process's
thread id, or TID_ERROR if the thread cannot be created. */
tid_t
process_execute (const char *file_name)
{
struct thread* cur = thread_current();
if (!is_initialized){
is_initialized = true;
list_init(&process_list);
list_init(&waiting_list);
initial_thread_tid = cur->tid;
}
char *fn_copy;
tid_t tid;
/* Make a copy of "FILE_NAME".
Otherwise there's a race between the caller and load(). */
fn_copy = palloc_get_page (0);
if (fn_copy == NULL)
return TID_ERROR;
strlcpy (fn_copy, file_name, PGSIZE);
/* Create a new thread to execute FILE_NAME. */
tid = thread_create (file_name, PRI_DEFAULT, start_process, fn_copy);
if (cur->tid != initial_thread_tid){
process *p = malloc(sizeof(process));
p->tid = tid;
p->parent_tid = cur->tid;
p->is_exited = false;
list_push_back(&process_list, &p->elem);
}
if (tid == TID_ERROR)
palloc_free_page (fn_copy);
return tid;
}
/* A thread function that loads a user process and starts it
running. */
static void
start_process (void *file_name_)
{
char *file_name = file_name_;
struct intr_frame if_;
bool success;
/////***** Argument Parsing *****/////
char *token, *save_ptr;
int argc=0;
int argv_data_size = 0;
char cp_file_name[strlen(file_name) + 1];
strlcpy(cp_file_name, file_name, strlen(file_name)+1);
for (token = strtok_r (file_name, " ", &save_ptr);
token != NULL;
token = strtok_r (NULL, " ", &save_ptr)){
argc++;
argv_data_size += strlen(token) +1; // +1 for '\0'
}
///////////////////////////////////////
/* Initialize interrupt frame and load executable. */
memset (&if_, 0, sizeof if_);
if_.gs = if_.fs = if_.es = if_.ds = if_.ss = SEL_UDSEG;
if_.cs = SEL_UCSEG;
if_.eflags = FLAG_IF | FLAG_MBS;
success = load (file_name, &if_.eip, &if_.esp);
if (success){
/////***** Argument Passing *****/////
char* data_adr = if_.esp;
data_adr = data_adr - argv_data_size;
int word_align = (argv_data_size % 4 == 0) ? 0 : 4 - (argv_data_size % 4);
uint32_t* argv_adr = (uint32_t*)(data_adr - word_align);
argv_adr = argv_adr - (argc+1);
int i;
for (i = 0;i < word_align;i++){
*(data_adr-i) = '\0';
}
i=0;
for (token = strtok_r (cp_file_name, " ", &save_ptr);
token != NULL;
token = strtok_r (NULL, " ", &save_ptr)){
int len = strlen(token) + 1;
strlcpy(data_adr, token, len);
*(argv_adr + i) = (uint32_t)data_adr;
data_adr += len;
i++;
}
*(argv_adr + argc) = 0;
*(argv_adr-1) = (uint32_t)argv_adr;
*(argv_adr-2) = argc;
*(argv_adr-3) = 0;
if_.esp = argv_adr-3;
}
///////////////////////////////////////
/* If load failed, quit. */
palloc_free_page (file_name);
if (!success)
thread_exit ();
struct file *code_file = filesys_open(file_name);
thread_current()->code_file = code_file;
if (code_file != NULL ) file_deny_write(code_file);
/* Start the user process by simulating a return from an
interrupt, implemented by intr_exit (in
threads/intr-stubs.S). Because intr_exit takes all of its
arguments on the stack in the form of a `struct intr_frame',
we just point the stack pointer %esp to our stack frame
and jump to it. */
asm volatile ("movl %0, %%esp; jmp intr_exit" : : "g" (&if_) : "memory");
NOT_REACHED ();
}
/* Waits for thread TID to die and returns its exit status. If
it was terminated by the kernel (i.e. killed due to an
exception), returns -1. If TID is invalid or if it was not a
child of the calling process, or if process_wait() has already
been successfully called for the given TID, returns -1
immediately, without waiting.
This function will be implemented in problem 2-2. For now, it
does nothing. */
int
process_wait (tid_t child_tid UNUSED)
{
struct thread *t = thread_current();
struct list_elem *e;
process *p = NULL;
for (e = list_begin(&process_list); e != list_end(&process_list); e
= list_next(e)) {
p = list_entry (e, process, elem);
if (p->tid != child_tid) continue;
// invalid parent
if (p->parent_tid != t->tid) return -1;
else break;
}
// no registered tid
if (e == list_end(&process_list)) return -1;
int exit_status;
if (p->is_exited){
exit_status = p->exit_status;
list_remove(e);
free(p);
return exit_status;
}
waiting_process *wp = malloc(sizeof(waiting_process));
wp->t = t;
wp->waiting_tid = child_tid;
enum intr_level old_level;
old_level = intr_disable ();
list_push_back(&waiting_list, &wp->elem);
thread_block();
intr_set_level (old_level);
exit_status = p->exit_status;
list_remove(e);
free(p);
return exit_status;
}
void set_process_exited (int exit_status){
struct thread *cur = thread_current ();
struct list_elem *e;
for (e = list_begin(&process_list); e != list_end(&process_list); e = list_next(e)) {
process *p = list_entry (e, process, elem);
if (p->tid == cur->tid){
p->is_exited = true;
p->exit_status = exit_status;
}
}
}
/* Free the current process's resources. */
void
process_exit (void)
{
struct thread *cur = thread_current ();
process *p = NULL;
// release this process's frames
frame_release(cur);
// await waiting this process
struct list_elem *e;
for (e = list_begin(&waiting_list); e != list_end(&waiting_list); e = list_next(e)) {
waiting_process *wp = list_entry(e, waiting_process, elem);
if (wp->waiting_tid == cur->tid){
thread_unblock(wp->t);
}
}
// remove child process's meta data
e = list_begin(&process_list);
while (e != list_end(&process_list)){
struct list_elem *next = list_next(e);
p = list_entry (e, process, elem);
if (p->parent_tid == cur->tid){
list_remove(e);
free(p);
}
e = next;
}
// close this process's opened files.
if (cur->fd_list.head.next != NULL){
while (!list_empty (&cur->fd_list))
{
e = list_pop_front (&cur->fd_list);
fd_element *fd_elem = list_entry (e, fd_element, elem);
file_close(fd_elem->file);
free(fd_elem);
}
}
// allow code file to can write.
if (cur->code_file != NULL){
file_allow_write(cur->code_file);
file_close(cur->code_file);
}
uint32_t *pd;
/* Destroys the current process's page directory and switch back
to the kernel-only page directory. */
pd = cur->pagedir;
if (pd != NULL)
{
/* Correct ordering here is crucial. We must set
cur->pagedir to NULL before switching page directories,
so that a timer interrupt can't switch back to the
process page directory. We must activate the base page
directory before destroying the process's page
directory, or our active page directory will be one
that's been freed (and cleared). */
cur->pagedir = NULL;
pagedir_activate (NULL);
pagedir_destroy (pd);
}
}
/* Sets up the CPU for running user code in the current
thread.
This function is called on every context switch. */
void
process_activate (void)
{
struct thread *t = thread_current ();
/* Activate thread's page tables. */
pagedir_activate (t->pagedir);
/* Set thread's kernel stack for use in processing
interrupts. */
tss_update ();
}
/* We load ELF binaries. The following definitions are taken
from the ELF specification, [ELF1], more-or-less verbatim. */
/* ELF types. See [ELF1] 1-2. */
typedef uint32_t Elf32_Word, Elf32_Addr, Elf32_Off;
typedef uint16_t Elf32_Half;
/* For use with ELF types in printf(). */
#define PE32Wx PRIx32 /* Print Elf32_Word in hexadecimal. */
#define PE32Ax PRIx32 /* Print Elf32_Addr in hexadecimal. */
#define PE32Ox PRIx32 /* Print Elf32_Off in hexadecimal. */
#define PE32Hx PRIx16 /* Print Elf32_Half in hexadecimal. */
/* Executable header. See [ELF1] 1-4 to 1-8.
This appears at the very beginning of an ELF binary. */
struct Elf32_Ehdr
{
unsigned char e_ident[16];
Elf32_Half e_type;
Elf32_Half e_machine;
Elf32_Word e_version;
Elf32_Addr e_entry;
Elf32_Off e_phoff;
Elf32_Off e_shoff;
Elf32_Word e_flags;
Elf32_Half e_ehsize;
Elf32_Half e_phentsize;
Elf32_Half e_phnum;
Elf32_Half e_shentsize;
Elf32_Half e_shnum;
Elf32_Half e_shstrndx;
};
/* Program header. See [ELF1] 2-2 to 2-4.
There are e_phnum of these, starting at file offset e_phoff
(see [ELF1] 1-6). */
struct Elf32_Phdr
{
Elf32_Word p_type;
Elf32_Off p_offset;
Elf32_Addr p_vaddr;
Elf32_Addr p_paddr;
Elf32_Word p_filesz;
Elf32_Word p_memsz;
Elf32_Word p_flags;
Elf32_Word p_align;
};
/* Values for p_type. See [ELF1] 2-3. */
#define PT_NULL 0 /* Ignore. */
#define PT_LOAD 1 /* Loadable segment. */
#define PT_DYNAMIC 2 /* Dynamic linking info. */
#define PT_INTERP 3 /* Name of dynamic loader. */
#define PT_NOTE 4 /* Auxiliary info. */
#define PT_SHLIB 5 /* Reserved. */
#define PT_PHDR 6 /* Program header table. */
#define PT_STACK 0x6474e551 /* Stack segment. */
/* Flags for p_flags. See [ELF3] 2-3 and 2-4. */
#define PF_X 1 /* Executable. */
#define PF_W 2 /* Writable. */
#define PF_R 4 /* Readable. */
static bool setup_stack (void **esp);
static bool validate_segment (const struct Elf32_Phdr *, struct file *);
static bool load_segment (struct file *file, off_t ofs, uint8_t *upage,
uint32_t read_bytes, uint32_t zero_bytes,
bool writable);
/* Loads an ELF executable from FILE_NAME into the current thread.
Stores the executable's entry point into *EIP
and its initial stack pointer into *ESP.
Returns true if successful, false otherwise. */
bool
load (const char *file_name, void (**eip) (void), void **esp)
{
struct thread *t = thread_current ();
struct Elf32_Ehdr ehdr;
struct file *file = NULL;
off_t file_ofs;
bool success = false;
int i;
/* Allocate and activate page directories. */
t->pagedir = pagedir_create ();
if (t->pagedir == NULL)
goto done;
process_activate ();
/* Open executable file. */
file = filesys_open (file_name);
if (file == NULL)
{
printf ("load: %s: open failed\n", file_name);
goto done;
}
/* Read and verify executable header. */
if (file_read (file, &ehdr, sizeof ehdr) != sizeof ehdr
|| memcmp (ehdr.e_ident, "\177ELF\1\1\1", 7)
|| ehdr.e_type != 2
|| ehdr.e_machine != 3
|| ehdr.e_version != 1
|| ehdr.e_phentsize != sizeof (struct Elf32_Phdr)
|| ehdr.e_phnum > 1024)
{
printf ("load: %s: error loading executable\n", file_name);
goto done;
}
/* Read program headers. */
file_ofs = ehdr.e_phoff;
for (i = 0; i < ehdr.e_phnum; i++)
{
struct Elf32_Phdr phdr;
if (file_ofs < 0 || file_ofs > file_length (file))
goto done;
file_seek (file, file_ofs);
if (file_read (file, &phdr, sizeof phdr) != sizeof phdr)
goto done;
file_ofs += sizeof phdr;
switch (phdr.p_type)
{
case PT_NULL:
case PT_NOTE:
case PT_PHDR:
case PT_STACK:
default:
/* Ignore this segment. */
break;
case PT_DYNAMIC:
case PT_INTERP:
case PT_SHLIB:
goto done;
case PT_LOAD:
if (validate_segment (&phdr, file))
{
bool writable = (phdr.p_flags & PF_W) != 0;
uint32_t file_page = phdr.p_offset & ~PGMASK;
uint32_t mem_page = phdr.p_vaddr & ~PGMASK;
uint32_t page_offset = phdr.p_vaddr & PGMASK;
uint32_t read_bytes, zero_bytes;
if (phdr.p_filesz > 0)
{
/* Normal segment.
Read initial part from disk and zero the rest. */
read_bytes = page_offset + phdr.p_filesz;
zero_bytes = (ROUND_UP (page_offset + phdr.p_memsz, PGSIZE)
- read_bytes);
}
else
{
/* Entirely zero
Don't read anything from disk. */
read_bytes = 0;
zero_bytes = ROUND_UP (page_offset + phdr.p_memsz, PGSIZE);
}
if (!load_segment (file, file_page, (void *) mem_page,
read_bytes, zero_bytes, writable))
goto done;
}
else
goto done;
break;
}
}
/* Set up stack. */
if (!setup_stack (esp))
goto done;
/* Start address. */
*eip = (void (*) (void)) ehdr.e_entry;
success = true;
done:
/* We arrive here whether the load is successful or not. */
file_close (file);
return success;
}
/* load() helpers. */
/* Checks whether PHDR describes a valid, loadable segment in
FILE and returns true if so, false otherwise. */
static bool
validate_segment (const struct Elf32_Phdr *phdr, struct file *file)
{
/* p_offset and p_vaddr must have the same page offset. */
if ((phdr->p_offset & PGMASK) != (phdr->p_vaddr & PGMASK))
return false;
/* p_offset must point within FILE. */
if (phdr->p_offset > (Elf32_Off) file_length (file))
return false;
/* p_memsz must be at least as big as p_filesz. */
if (phdr->p_memsz < phdr->p_filesz)
return false;
/* The segment must not be empty. */
if (phdr->p_memsz == 0)
return false;
/* The virtual memory region must both start and end within the
user address space range. */
if (!is_user_vaddr ((void *) phdr->p_vaddr))
return false;
if (!is_user_vaddr ((void *) (phdr->p_vaddr + phdr->p_memsz)))
return false;
/* The region cannot "wrap around" across the kernel virtual
address space. */
if (phdr->p_vaddr + phdr->p_memsz < phdr->p_vaddr)
return false;
/* Disallow mapping page 0.
Not only is it a bad idea to map page 0, but if we allowed
it then user code that passed a null pointer to system calls
could quite likely panic the kernel by way of null pointer
assertions in memcpy(), etc. */
//if (phdr->p_vaddr < PGSIZE)
//return false;
/* It's okay. */
return true;
}
/* Loads a segment starting at offset OFS in FILE at address
UPAGE. In total, READ_BYTES + ZERO_BYTES bytes of virtual
memory are initialized, as follows:
- READ_BYTES bytes at UPAGE must be read from FILE
starting at offset OFS.
- ZERO_BYTES bytes at UPAGE + READ_BYTES must be zeroed.
The pages initialized by this function must be writable by the
user process if WRITABLE is true, read-only otherwise.
Return true if successful, false if a memory allocation error
or disk read error occurs. */
static bool
load_segment (struct file *file, off_t ofs, uint8_t *upage,
uint32_t read_bytes, uint32_t zero_bytes, bool writable)
{
ASSERT ((read_bytes + zero_bytes) % PGSIZE == 0);
ASSERT (pg_ofs (upage) == 0);
ASSERT (ofs % PGSIZE == 0);
struct thread* t = thread_current();
file_seek (file, ofs);
while (read_bytes > 0 || zero_bytes > 0)
{
/* Calculate how to fill this page.
We will read PAGE_READ_BYTES bytes from FILE
and zero the final PAGE_ZERO_BYTES bytes. */
size_t page_read_bytes = read_bytes < PGSIZE ? read_bytes : PGSIZE;
size_t page_zero_bytes = PGSIZE - page_read_bytes;
/* Get a page from memory. */
if (!frame_allocate_new(upage, writable)) return false;
uint8_t *kpage = pagedir_get_page(t->pagedir, upage);
if (kpage == NULL)
return false;
/* Load this page. */
if (file_read (file, kpage, page_read_bytes) != (int) page_read_bytes)
{
palloc_free_page (kpage);
return false;
}
memset (kpage + page_read_bytes, 0, page_zero_bytes);
/* Advance. */
read_bytes -= page_read_bytes;
zero_bytes -= page_zero_bytes;
upage += PGSIZE;
}
return true;
}
/* Create a minimal stack by mapping a zeroed page at the top of
user virtual memory. */
static bool
setup_stack (void **esp)
{
bool success = false;
void* upage = (((uint8_t *) PHYS_BASE) - PGSIZE);
success = frame_allocate_new(upage, true);
if (success){
*esp = PHYS_BASE;
thread_current()->low_esp = upage;
}
return success;
}
| 10cm | trunk/10cm/pintos/src/userprog/process.c | C | oos | 17,745 |
#ifndef USERPROG_SYSCALL_H
#define USERPROG_SYSCALL_H
void syscall_init (void);
#endif /* userprog/syscall.h */
| 10cm | trunk/10cm/pintos/src/userprog/syscall.h | C | oos | 115 |
#include "userprog/pagedir.h"
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include "threads/init.h"
#include "threads/pte.h"
#include "threads/palloc.h"
static uint32_t *active_pd (void);
static void invalidate_pagedir (uint32_t *);
/* Creates a new page directory that has mappings for kernel
virtual addresses, but none for user virtual addresses.
Returns the new page directory, or a null pointer if memory
allocation fails. */
uint32_t *
pagedir_create (void)
{
uint32_t *pd = palloc_get_page (0);
if (pd != NULL)
memcpy (pd, base_page_dir, PGSIZE);
return pd;
}
/* Destroys page directory PD, freeing all the pages it
references. */
void
pagedir_destroy (uint32_t *pd)
{
uint32_t *pde;
if (pd == NULL)
return;
ASSERT (pd != base_page_dir);
for (pde = pd; pde < pd + pd_no (PHYS_BASE); pde++)
if (*pde & PTE_P)
{
uint32_t *pt = pde_get_pt (*pde);
uint32_t *pte;
for (pte = pt; pte < pt + PGSIZE / sizeof *pte; pte++)
if (*pte & PTE_P)
palloc_free_page (pte_get_page (*pte));
palloc_free_page (pt);
}
palloc_free_page (pd);
}
/* Returns the address of the page table entry for virtual
address VADDR in page directory PD.
If PD does not have a page table for VADDR, behavior depends
on CREATE. If CREATE is true, then a new page table is
created and a pointer into it is returned. Otherwise, a null
pointer is returned. */
static uint32_t *
lookup_page (uint32_t *pd, const void *vaddr, bool create)
{
uint32_t *pt, *pde;
ASSERT (pd != NULL);
/* Shouldn't create new kernel virtual mappings. */
ASSERT (!create || is_user_vaddr (vaddr));
/* Check for a page table for VADDR.
If one is missing, create one if requested. */
pde = pd + pd_no (vaddr);
if (*pde == 0)
{
if (create)
{
pt = palloc_get_page (PAL_ZERO);
if (pt == NULL)
return NULL;
*pde = pde_create (pt);
}
else
return NULL;
}
/* Return the page table entry. */
pt = pde_get_pt (*pde);
return &pt[pt_no (vaddr)];
}
/* Adds a mapping in page directory PD from user virtual page
UPAGE to the physical frame identified by kernel virtual
address KPAGE.
UPAGE must not already be mapped.
KPAGE should probably be a page obtained from the user pool
with palloc_get_page().
If WRITABLE is true, the new page is read/write;
otherwise it is read-only.
Returns true if successful, false if memory allocation
failed. */
bool
pagedir_set_page (uint32_t *pd, void *upage, void *kpage, bool writable)
{
uint32_t *pte;
ASSERT (pg_ofs (upage) == 0);
ASSERT (pg_ofs (kpage) == 0);
ASSERT (is_user_vaddr (upage));
ASSERT (vtop (kpage) >> PTSHIFT < ram_pages);
ASSERT (pd != base_page_dir);
pte = lookup_page (pd, upage, true);
if (pte != NULL)
{
ASSERT ((*pte & PTE_P) == 0);
*pte = pte_create_user (kpage, writable);
return true;
}
else
return false;
}
/* Looks up the physical address that corresponds to user virtual
address UADDR in PD. Returns the kernel virtual address
corresponding to that physical address, or a null pointer if
UADDR is unmapped. */
void *
pagedir_get_page (uint32_t *pd, const void *uaddr)
{
uint32_t *pte;
ASSERT (is_user_vaddr (uaddr));
pte = lookup_page (pd, uaddr, false);
if (pte != NULL && (*pte & PTE_P) != 0)
return pte_get_page (*pte) + pg_ofs (uaddr);
else
return NULL;
}
/* Marks user virtual page UPAGE "not present" in page
directory PD. Later accesses to the page will fault. Other
bits in the page table entry are preserved.
UPAGE need not be mapped. */
void
pagedir_clear_page (uint32_t *pd, void *upage)
{
uint32_t *pte;
ASSERT (pg_ofs (upage) == 0);
ASSERT (is_user_vaddr (upage));
pte = lookup_page (pd, upage, false);
if (pte != NULL && (*pte & PTE_P) != 0)
{
*pte &= ~PTE_P;
invalidate_pagedir (pd);
}
}
/* Returns true if the PTE for virtual page VPAGE in PD is dirty,
that is, if the page has been modified since the PTE was
installed.
Returns false if PD contains no PTE for VPAGE. */
bool
pagedir_is_dirty (uint32_t *pd, const void *vpage)
{
uint32_t *pte = lookup_page (pd, vpage, false);
return pte != NULL && (*pte & PTE_D) != 0;
}
/* Set the dirty bit to DIRTY in the PTE for virtual page VPAGE
in PD. */
void
pagedir_set_dirty (uint32_t *pd, const void *vpage, bool dirty)
{
uint32_t *pte = lookup_page (pd, vpage, false);
if (pte != NULL)
{
if (dirty)
*pte |= PTE_D;
else
{
*pte &= ~(uint32_t) PTE_D;
invalidate_pagedir (pd);
}
}
}
/* Returns true if the PTE for virtual page VPAGE in PD has been
accessed recently, that is, between the time the PTE was
installed and the last time it was cleared. Returns false if
PD contains no PTE for VPAGE. */
bool
pagedir_is_accessed (uint32_t *pd, const void *vpage)
{
uint32_t *pte = lookup_page (pd, vpage, false);
return pte != NULL && (*pte & PTE_A) != 0;
}
/* Sets the accessed bit to ACCESSED in the PTE for virtual page
VPAGE in PD. */
void
pagedir_set_accessed (uint32_t *pd, const void *vpage, bool accessed)
{
uint32_t *pte = lookup_page (pd, vpage, false);
if (pte != NULL)
{
if (accessed)
*pte |= PTE_A;
else
{
*pte &= ~(uint32_t) PTE_A;
invalidate_pagedir (pd);
}
}
}
/* Loads page directory PD into the CPU's page directory base
register. */
void
pagedir_activate (uint32_t *pd)
{
if (pd == NULL)
pd = base_page_dir;
/* Store the physical address of the page directory into CR3
aka PDBR (page directory base register). This activates our
new page tables immediately. See [IA32-v2a] "MOV--Move
to/from Control Registers" and [IA32-v3a] 3.7.5 "Base
Address of the Page Directory". */
asm volatile ("movl %0, %%cr3" : : "r" (vtop (pd)) : "memory");
}
/* Returns the currently active page directory. */
static uint32_t *
active_pd (void)
{
/* Copy CR3, the page directory base register (PDBR), into
`pd'.
See [IA32-v2a] "MOV--Move to/from Control Registers" and
[IA32-v3a] 3.7.5 "Base Address of the Page Directory". */
uintptr_t pd;
asm volatile ("movl %%cr3, %0" : "=r" (pd));
return ptov (pd);
}
/* Seom page table changes can cause the CPU's translation
lookaside buffer (TLB) to become out-of-sync with the page
table. When this happens, we have to "invalidate" the TLB by
re-activating it.
This function invalidates the TLB if PD is the active page
directory. (If PD is not active then its entries are not in
the TLB, so there is no need to invalidate anything.) */
static void
invalidate_pagedir (uint32_t *pd)
{
if (active_pd () == pd)
{
/* Re-activating PD clears the TLB. See [IA32-v3a] 3.12
"Translation Lookaside Buffers (TLBs)" */
pagedir_activate (pd);
}
}
| 10cm | trunk/10cm/pintos/src/userprog/pagedir.c | C | oos | 7,068 |
#ifndef USERPROG_PAGEDIR_H
#define USERPROG_PAGEDIR_H
#include <stdbool.h>
#include <stdint.h>
uint32_t *pagedir_create (void);
void pagedir_destroy (uint32_t *pd);
bool pagedir_set_page (uint32_t *pd, void *upage, void *kpage, bool rw);
void *pagedir_get_page (uint32_t *pd, const void *upage);
void pagedir_clear_page (uint32_t *pd, void *upage);
bool pagedir_is_dirty (uint32_t *pd, const void *upage);
void pagedir_set_dirty (uint32_t *pd, const void *upage, bool dirty);
bool pagedir_is_accessed (uint32_t *pd, const void *upage);
void pagedir_set_accessed (uint32_t *pd, const void *upage, bool accessed);
void pagedir_activate (uint32_t *pd);
#endif /* userprog/pagedir.h */
| 10cm | trunk/10cm/pintos/src/userprog/pagedir.h | C | oos | 686 |
#ifndef USERPROG_EXCEPTION_H
#define USERPROG_EXCEPTION_H
/* Page fault error code bits that describe the cause of the exceptions. */
#define PF_P 0x1 /* 0: not-present page. 1: access rights violation. */
#define PF_W 0x2 /* 0: read, 1: write. */
#define PF_U 0x4 /* 0: kernel, 1: user process. */
void exception_init (void);
void exception_print_stats (void);
#endif /* userprog/exception.h */
| 10cm | trunk/10cm/pintos/src/userprog/exception.h | C | oos | 409 |
include ../Makefile.kernel
| 10cm | trunk/10cm/pintos/src/userprog/Makefile | Makefile | oos | 27 |
#include "userprog/gdt.h"
#include <debug.h>
#include "userprog/tss.h"
#include "threads/palloc.h"
#include "threads/vaddr.h"
/* The Global Descriptor Table (GDT).
The GDT, an x86-specific structure, defines segments that can
potentially be used by all processes in a system, subject to
their permissions. There is also a per-process Local
Descriptor Table (LDT) but that is not used by modern
operating systems.
Each entry in the GDT, which is known by its byte offset in
the table, identifies a segment. For our purposes only three
types of segments are of interest: code, data, and TSS or
Task-State Segment descriptors. The former two types are
exactly what they sound like. The TSS is used primarily for
stack switching on interrupts.
For more information on the GDT as used here, refer to
[IA32-v3a] 3.2 "Using Segments" through 3.5 "System Descriptor
Types". */
static uint64_t gdt[SEL_CNT];
/* GDT helpers. */
static uint64_t make_code_desc (int dpl);
static uint64_t make_data_desc (int dpl);
static uint64_t make_tss_desc (void *laddr);
static uint64_t make_gdtr_operand (uint16_t limit, void *base);
/* Sets up a proper GDT. The bootstrap loader's GDT didn't
include user-mode selectors or a TSS, but we need both now. */
void
gdt_init (void)
{
uint64_t gdtr_operand;
/* Initialize GDT. */
gdt[SEL_NULL / sizeof *gdt] = 0;
gdt[SEL_KCSEG / sizeof *gdt] = make_code_desc (0);
gdt[SEL_KDSEG / sizeof *gdt] = make_data_desc (0);
gdt[SEL_UCSEG / sizeof *gdt] = make_code_desc (3);
gdt[SEL_UDSEG / sizeof *gdt] = make_data_desc (3);
gdt[SEL_TSS / sizeof *gdt] = make_tss_desc (tss_get ());
/* Load GDTR, TR. See [IA32-v3a] 2.4.1 "Global Descriptor
Table Register (GDTR)", 2.4.4 "Task Register (TR)", and
6.2.4 "Task Register". */
gdtr_operand = make_gdtr_operand (sizeof gdt - 1, gdt);
asm volatile ("lgdt %0" : : "m" (gdtr_operand));
asm volatile ("ltr %w0" : : "q" (SEL_TSS));
}
/* System segment or code/data segment? */
enum seg_class
{
CLS_SYSTEM = 0, /* System segment. */
CLS_CODE_DATA = 1 /* Code or data segment. */
};
/* Limit has byte or 4 kB page granularity? */
enum seg_granularity
{
GRAN_BYTE = 0, /* Limit has 1-byte granularity. */
GRAN_PAGE = 1 /* Limit has 4 kB granularity. */
};
/* Returns a segment descriptor with the given 32-bit BASE and
20-bit LIMIT (whose interpretation depends on GRANULARITY).
The descriptor represents a system or code/data segment
according to CLASS, and TYPE is its type (whose interpretation
depends on the class).
The segment has descriptor privilege level DPL, meaning that
it can be used in rings numbered DPL or lower. In practice,
DPL==3 means that user processes can use the segment and
DPL==0 means that only the kernel can use the segment. See
[IA32-v3a] 4.5 "Privilege Levels" for further discussion. */
static uint64_t
make_seg_desc (uint32_t base,
uint32_t limit,
enum seg_class class,
int type,
int dpl,
enum seg_granularity granularity)
{
uint32_t e0, e1;
ASSERT (limit <= 0xfffff);
ASSERT (class == CLS_SYSTEM || class == CLS_CODE_DATA);
ASSERT (type >= 0 && type <= 15);
ASSERT (dpl >= 0 && dpl <= 3);
ASSERT (granularity == GRAN_BYTE || granularity == GRAN_PAGE);
e0 = ((limit & 0xffff) /* Limit 15:0. */
| (base << 16)); /* Base 15:0. */
e1 = (((base >> 16) & 0xff) /* Base 23:16. */
| (type << 8) /* Segment type. */
| (class << 12) /* 0=system, 1=code/data. */
| (dpl << 13) /* Descriptor privilege. */
| (1 << 15) /* Present. */
| (limit & 0xf0000) /* Limit 16:19. */
| (1 << 22) /* 32-bit segment. */
| (granularity << 23) /* Byte/page granularity. */
| (base & 0xff000000)); /* Base 31:24. */
return e0 | ((uint64_t) e1 << 32);
}
/* Returns a descriptor for a readable code segment with base at
0, a limit of 4 GB, and the given DPL. */
static uint64_t
make_code_desc (int dpl)
{
return make_seg_desc (0, 0xfffff, CLS_CODE_DATA, 10, dpl, GRAN_PAGE);
}
/* Returns a descriptor for a writable data segment with base at
0, a limit of 4 GB, and the given DPL. */
static uint64_t
make_data_desc (int dpl)
{
return make_seg_desc (0, 0xfffff, CLS_CODE_DATA, 2, dpl, GRAN_PAGE);
}
/* Returns a descriptor for an "available" 32-bit Task-State
Segment with its base at the given linear address, a limit of
0x67 bytes (the size of a 32-bit TSS), and a DPL of 0.
See [IA32-v3a] 6.2.2 "TSS Descriptor". */
static uint64_t
make_tss_desc (void *laddr)
{
return make_seg_desc ((uint32_t) laddr, 0x67, CLS_SYSTEM, 9, 0, GRAN_BYTE);
}
/* Returns a descriptor that yields the given LIMIT and BASE when
used as an operand for the LGDT instruction. */
static uint64_t
make_gdtr_operand (uint16_t limit, void *base)
{
return limit | ((uint64_t) (uint32_t) base << 16);
}
| 10cm | trunk/10cm/pintos/src/userprog/gdt.c | C | oos | 5,156 |
# -*- makefile -*-
$(PROGS): CPPFLAGS += -I$(SRCDIR)/lib/user -I.
# Linker flags.
$(PROGS): LDFLAGS += -nostdlib -static -Wl,-T,$(LDSCRIPT)
$(PROGS): LDSCRIPT = $(SRCDIR)/lib/user/user.lds
# Library code shared between kernel and user programs.
lib_SRC = lib/debug.c # Debug code.
lib_SRC += lib/random.c # Pseudo-random numbers.
lib_SRC += lib/stdio.c # I/O library.
lib_SRC += lib/stdlib.c # Utility functions.
lib_SRC += lib/string.c # String functions.
lib_SRC += lib/arithmetic.c # 64-bit arithmetic for GCC.
lib_SRC += lib/ustar.c # Unix standard tar format utilities.
# User level only library code.
lib/user_SRC = lib/user/debug.c # Debug helpers.
lib/user_SRC += lib/user/syscall.c # System calls.
lib/user_SRC += lib/user/console.c # Console code.
LIB_OBJ = $(patsubst %.c,%.o,$(patsubst %.S,%.o,$(lib_SRC) $(lib/user_SRC)))
LIB_DEP = $(patsubst %.o,%.d,$(LIB_OBJ))
LIB = lib/user/entry.o libc.a
PROGS_SRC = $(foreach prog,$(PROGS),$($(prog)_SRC))
PROGS_OBJ = $(patsubst %.c,%.o,$(patsubst %.S,%.o,$(PROGS_SRC)))
PROGS_DEP = $(patsubst %.o,%.d,$(PROGS_OBJ))
all: $(PROGS)
define TEMPLATE
$(1)_OBJ = $(patsubst %.c,%.o,$(patsubst %.S,%.o,$($(1)_SRC)))
$(1): $$($(1)_OBJ) $$(LIB) $$(LDSCRIPT)
$$(CC) $$(LDFLAGS) $$($(1)_OBJ) $$(LIB) -o $$@
endef
$(foreach prog,$(PROGS),$(eval $(call TEMPLATE,$(prog))))
libc.a: $(LIB_OBJ)
rm -f $@
ar r $@ $^
ranlib $@
clean::
rm -f $(PROGS) $(PROGS_OBJ) $(PROGS_DEP)
rm -f $(LIB_DEP) $(LIB_OBJ) lib/user/entry.[do] libc.a
.PHONY: all clean
-include $(LIB_DEP) $(PROGS_DEP)
| 10cm | trunk/10cm/pintos/src/.svn/text-base/Makefile.userprog.svn-base | Makefile | oos | 1,551 |
# -*- makefile -*-
SHELL = /bin/sh
VPATH = $(SRCDIR)
# Binary utilities.
# If the host appears to be x86, use the normal tools.
# If it's x86-64, use the compiler and linker in 32-bit mode.
# Otherwise assume cross-tools are installed as i386-elf-*.
X86 = i.86\|pentium.*\|[pk][56]\|nexgen\|viac3\|6x86\|athlon.*\|i86pc
X86_64 = x86_64
ifneq (0, $(shell expr `uname -m` : '$(X86)'))
CC = gcc
LD = ld
OBJCOPY = objcopy
else
ifneq (0, $(shell expr `uname -m` : '$(X86_64)'))
CC = gcc -m32
LD = ld -melf_i386
OBJCOPY = objcopy
else
CC = i386-elf-gcc
LD = i386-elf-ld
OBJCOPY = i386-elf-objcopy
endif
endif
ifeq ($(strip $(shell command -v $(CC) 2> /dev/null)),)
$(warning *** Compiler ($(CC)) not found. Did you set $$PATH properly? Please refer to the Getting Started section in the documentation for details. ***)
endif
# Compiler and assembler invocation.
DEFINES =
WARNINGS = -Wall -W -Wstrict-prototypes -Wmissing-prototypes -Wsystem-headers
CFLAGS = -g -msoft-float -O
CPPFLAGS = -nostdinc -I$(SRCDIR) -I$(SRCDIR)/lib
ASFLAGS = -Wa,--gstabs
LDFLAGS =
DEPS = -MMD -MF $(@:.o=.d)
# Turn off -fstack-protector, which we don't support.
ifeq ($(strip $(shell echo | $(CC) -fno-stack-protector -E - > /dev/null 2>&1; echo $$?)),0)
CFLAGS += -fno-stack-protector
endif
# Turn off --build-id in the linker, which confuses the Pintos loader.
ifeq ($(strip $(shell $(LD) --build-id=none -e 0 /dev/null -o /dev/null 2>&1; echo $$?)),0)
LDFLAGS += -Wl,--build-id=none
endif
%.o: %.c
$(CC) -c $< -o $@ $(CFLAGS) $(CPPFLAGS) $(WARNINGS) $(DEFINES) $(DEPS)
%.o: %.S
$(CC) -c $< -o $@ $(ASFLAGS) $(CPPFLAGS) $(DEFINES) $(DEPS)
| 10cm | trunk/10cm/pintos/src/.svn/text-base/Make.config.svn-base | Makefile | oos | 1,664 |
# -*- makefile -*-
SRCDIR = ../..
all: os.dsk
include ../../Make.config
include ../Make.vars
include ../../tests/Make.tests
# Compiler and assembler options.
os.dsk: CPPFLAGS += -I$(SRCDIR)/lib/kernel
# Core kernel.
threads_SRC = threads/init.c # Main program.
threads_SRC += threads/thread.c # Thread management core.
threads_SRC += threads/switch.S # Thread switch routine.
threads_SRC += threads/interrupt.c # Interrupt core.
threads_SRC += threads/intr-stubs.S # Interrupt stubs.
threads_SRC += threads/synch.c # Synchronization.
threads_SRC += threads/palloc.c # Page allocator.
threads_SRC += threads/malloc.c # Subpage allocator.
threads_SRC += threads/start.S # Startup code.
# Device driver code.
devices_SRC = devices/timer.c # Timer device.
devices_SRC += devices/kbd.c # Keyboard device.
devices_SRC += devices/vga.c # Video device.
devices_SRC += devices/serial.c # Serial port device.
devices_SRC += devices/disk.c # IDE disk device.
devices_SRC += devices/input.c # Serial and keyboard input.
devices_SRC += devices/intq.c # Interrupt queue.
devices_SRC += devices/rtc.c # Real-time clock.
# Library code shared between kernel and user programs.
lib_SRC = lib/debug.c # Debug helpers.
lib_SRC += lib/random.c # Pseudo-random numbers.
lib_SRC += lib/stdio.c # I/O library.
lib_SRC += lib/stdlib.c # Utility functions.
lib_SRC += lib/string.c # String functions.
lib_SRC += lib/arithmetic.c # 64-bit arithmetic for GCC.
lib_SRC += lib/ustar.c # Unix standard tar format utilities.
# Kernel-specific library code.
lib/kernel_SRC = lib/kernel/debug.c # Debug helpers.
lib/kernel_SRC += lib/kernel/list.c # Doubly-linked lists.
lib/kernel_SRC += lib/kernel/bitmap.c # Bitmaps.
lib/kernel_SRC += lib/kernel/hash.c # Hash tables.
lib/kernel_SRC += lib/kernel/console.c # printf(), putchar().
# User process code.
userprog_SRC = userprog/process.c # Process loading.
userprog_SRC += userprog/pagedir.c # Page directories.
userprog_SRC += userprog/exception.c # User exception handler.
userprog_SRC += userprog/syscall.c # System call handler.
userprog_SRC += userprog/gdt.c # GDT initialization.
userprog_SRC += userprog/tss.c # TSS management.
# No virtual memory code yet.
vm_SRC = vm/frame.c # Some file.
vm_SRC += vm/swap.c # Some file.
# Filesystem code.
filesys_SRC = filesys/filesys.c # Filesystem core.
filesys_SRC += filesys/free-map.c # Free sector bitmap.
filesys_SRC += filesys/file.c # Files.
filesys_SRC += filesys/directory.c # Directories.
filesys_SRC += filesys/inode.c # File headers.
filesys_SRC += filesys/fsutil.c # Utilities.
filesys_SRC += filesys/cache.c # Buffer Cache
SOURCES = $(foreach dir,$(KERNEL_SUBDIRS),$($(dir)_SRC))
OBJECTS = $(patsubst %.c,%.o,$(patsubst %.S,%.o,$(SOURCES)))
DEPENDS = $(patsubst %.o,%.d,$(OBJECTS))
threads/kernel.lds.s: CPPFLAGS += -P
threads/kernel.lds.s: threads/kernel.lds.S threads/loader.h
kernel.o: threads/kernel.lds.s $(OBJECTS)
$(LD) -T $< -o $@ $(OBJECTS)
kernel.bin: kernel.o
$(OBJCOPY) -O binary -R .note -R .comment -S $< $@.tmp
dd if=$@.tmp of=$@ bs=4096 conv=sync
rm $@.tmp
threads/loader.o: threads/loader.S kernel.bin
$(CC) -c $< -o $@ $(ASFLAGS) $(CPPFLAGS) $(DEFINES) -DKERNEL_LOAD_PAGES=`perl -e 'print +(-s "kernel.bin") / 4096;'`
loader.bin: threads/loader.o
$(LD) -N -e start -Ttext 0x7c00 --oformat binary -o $@ $<
os.dsk: loader.bin kernel.bin
cat $^ > $@
clean::
rm -f $(OBJECTS) $(DEPENDS)
rm -f threads/loader.o threads/kernel.lds.s threads/loader.d
rm -f kernel.o kernel.lds.s
rm -f kernel.bin loader.bin os.dsk
rm -f bochsout.txt bochsrc.txt
rm -f results grade
Makefile: $(SRCDIR)/Makefile.build
cp $< $@
-include $(DEPENDS)
| 10cm | trunk/10cm/pintos/src/.svn/text-base/Makefile.build.svn-base | Makefile | oos | 3,699 |
# -*- makefile -*-
all:
include Make.vars
DIRS = $(sort $(addprefix build/,$(KERNEL_SUBDIRS) $(TEST_SUBDIRS) lib/user))
all grade check: $(DIRS) build/Makefile
cd build && $(MAKE) $@
$(DIRS):
mkdir -p $@
build/Makefile: ../Makefile.build
cp $< $@
build/%: $(DIRS) build/Makefile
cd build && $(MAKE) $*
clean:
rm -rf build
| 10cm | trunk/10cm/pintos/src/.svn/text-base/Makefile.kernel.svn-base | Makefile | oos | 333 |
#ifndef VM_FRAME_H_
#define VM_FRAME_H_
#include "threads/thread.h"
void frame_init(void);
bool frame_allocate_new(void*, bool);
bool frame_load(void*);
void frame_release(struct thread* t);
struct frame{
void *kpage;
struct thread* t;
void *upage;
bool writable;
struct list_elem elem;
};
struct frame* pick_evict_frame(void);
#endif /* VM_FRAME_H_ */
| 10cm | trunk/10cm/pintos/src/vm/frame.h | C | oos | 363 |
# -*- makefile -*-
os.dsk: DEFINES = -DUSERPROG -DFILESYS -DVM
KERNEL_SUBDIRS = threads devices lib lib/kernel userprog filesys vm
TEST_SUBDIRS = tests/userprog tests/vm tests/filesys/base
GRADING_FILE = $(SRCDIR)/tests/vm/Grading
SIMULATOR = --qemu
| 10cm | trunk/10cm/pintos/src/vm/Make.vars | Makefile | oos | 251 |
#include "vm/swap.h"
#include "vm/frame.h"
#include "threads/palloc.h"
#include "threads/malloc.h"
#include "threads/thread.h"
#include "threads/vaddr.h"
#include "devices/disk.h"
#include "userprog/pagedir.h"
#include <bitmap.h>
#include <stdio.h>
/* 한 페이지가 몇개의 데이터 섹터를 차지하는지에 대한 값 */
#define PAGE_SECTOR_SIZE (PGSIZE / DISK_SECTOR_SIZE)
struct list page_list;
struct disk *swap_disk;
struct bitmap *swap_bitmap;
void swap_init() {
list_init(&page_list);
// swap disk를 가져온다.
swap_disk = disk_get(1, 1);
ASSERT(swap_disk != NULL);
// disk의 크기를 구한다.
disk_sector_t swap_disk_size = disk_size(swap_disk);
// 현재 disk의 크기에 몇개의 page까지 들어 갈 수 있는지 구한다.
size_t swap_page_size = swap_disk_size / PAGE_SECTOR_SIZE;
// 그 크기만큼의 bitmap을 생성하여 해당 disk 영역이 할당됐는지 아닌지를 저장한다.
swap_bitmap = bitmap_create(swap_page_size);
ASSERT(swap_bitmap != NULL);
}
struct page* swap_get_page(struct thread* t, void* upage) {
// 리스트를 돌면서 이 쓰레드의 upage위치에 대한 페이지 정보가 있는지 찾는다.
struct list_elem *e;
for (e = list_begin(&page_list); e != list_end(&page_list); e
= list_next(e)) {
struct page *p = list_entry (e, struct page, elem);
if (p->t == t && p->upage == upage) {
return p;
}
}
return NULL;
}
bool swap_in_page(struct page* p) {
if (p == NULL) return false;
// 이 페이지에 해당하는 디스크 내용을 메모리로 복사한다.
int i;
for (i = 0; i < PAGE_SECTOR_SIZE; i++){
disk_read(swap_disk, p->sector_index * PAGE_SECTOR_SIZE + i,
p->upage + i * DISK_SECTOR_SIZE);
}
return true;
}
bool swap_out_page(struct thread* t, void* upage, bool writable) {
// 이미 디스크에 이 page에 대한 정보가 저장되어 있는지 먼저 확인한다.
struct page* p = swap_get_page(t, upage);
if (p == NULL){
// bitmap 을 조사해서 현재 비었는 섹터 위치 하나를 가져오고
// 해당 위치를 사용중으로 표시한다. (scan and flip)
size_t sector_index = bitmap_scan_and_flip(swap_bitmap, 0, 1, false);
if (sector_index == BITMAP_ERROR){
printf("no more space in swap disk.\n");
return false;
}
// 이 페이지에 대한 정보를 저장하기 위한 구조체를 생성해서 리스트에 추가한다.
p = malloc(sizeof(struct frame));
p->t = t;
p->upage = upage;
p->sector_index = sector_index;
p->writable = writable;
list_push_back(&page_list, &p->elem);
} else {
// 그 사이에 변경되지 않았다면 굳이 값을 또 쓸 필요 없다.
if (!pagedir_is_dirty(t->pagedir, upage)) return true;
}
// 현재 쓰레드가 아닌 임의의 쓰레드 t의 메모리 영역에 접근해야 돼서
// virtual address가 아니라 kernel address를 통해 접근한다.
void* kpage = pagedir_get_page(t->pagedir, upage);
if (kpage == NULL) return false;
// kpage에 있는 내용을 지정된 디스크 섹터 위치에 쓴다.
int i;
for (i = 0; i < PAGE_SECTOR_SIZE; i++){
disk_write(swap_disk, p->sector_index * PAGE_SECTOR_SIZE + i,
kpage + i * DISK_SECTOR_SIZE);
}
return true;
}
void swap_release_pages(struct thread* t) {
// 페이지 리스트를 돌면서 이 쓰레드와 관련된 페이지들은 모두 해제하고 제거한다.
struct page* p;
struct list_elem *e = list_begin(&page_list);
while (e != list_end(&page_list)){
struct list_elem *next = list_next(e);
p = list_entry (e, struct page, elem);
if (p->t == t){
bitmap_reset (swap_bitmap, p->sector_index);
list_remove(e);
free(p);
}
e = next;
}
}
| 10cm | trunk/10cm/pintos/src/vm/swap.c | C | oos | 3,687 |
#ifndef VM_SWAP_H_
#define VM_SWAP_H_
#include "threads/thread.h"
void swap_init(void);
struct page* swap_get_page(struct thread* t, void* upage);
bool swap_in_page(struct page* p);
bool swap_out_page(struct thread* t, void* upage, bool writable);
void swap_release_pages(struct thread* t);
struct page{
struct thread* t;
void* upage;
bool writable;
size_t sector_index;
struct list_elem elem;
};
#endif /* VM_SWAP_H_ */
| 10cm | trunk/10cm/pintos/src/vm/swap.h | C | oos | 430 |
# -*- makefile -*-
os.dsk: DEFINES = -DUSERPROG -DFILESYS -DVM
KERNEL_SUBDIRS = threads devices lib lib/kernel userprog filesys vm
TEST_SUBDIRS = tests/userprog tests/vm tests/filesys/base
GRADING_FILE = $(SRCDIR)/tests/vm/Grading
SIMULATOR = --qemu
| 10cm | trunk/10cm/pintos/src/vm/.svn/text-base/Make.vars.svn-base | Makefile | oos | 251 |
#include "vm/frame.h"
#include "vm/swap.h"
#include "threads/palloc.h"
#include "threads/malloc.h"
#include "threads/thread.h"
#include "threads/vaddr.h"
#include "threads/pte.h"
#include "userprog/pagedir.h"
#include <stdio.h>
// LRU가 제대로 동작하는지 확인하려면 이 부분의 주석을 풀면 됩니다.
// ( _LRU_DEBUG_가 정의되면 swap in, swap out 시 log가 출력됨 )
//#define _LRU_DEBUG_
struct list frame_list;
struct frame *candidate;
bool frame_load_impl(void* upage, bool do_load, bool writable);
void frame_init(){
list_init(&frame_list);
candidate = NULL;
}
bool frame_allocate_new(void* upage, bool writable){
return frame_load_impl(upage, false, writable);
}
bool frame_load(void* upage){
// load의 경우에는 일단 읽어오기 위해 writable을 true로 핮미나
// 최종적인 writable 값은 기존 값을 사용하도록 된다.
return frame_load_impl(upage, true, true);
}
bool frame_load_impl(void* upage, bool do_load, bool writable){
struct thread *t = thread_current ();
// swap된걸 불러와야 한다면 저장된 페이지를 불러온다.
struct page* p = NULL;
if (do_load){
p = swap_get_page(t, upage);
if (p == NULL) return false;
}
struct frame* f = NULL;
uint8_t *kpage = palloc_get_page (PAL_USER | PAL_ZERO);
if (kpage == NULL){
// evict 할 프레임을 선정
f = pick_evict_frame();
// 해당 페이지의 내용을 디스크에 swap out
if (!swap_out_page(f->t, f->upage, f->writable)) return false;
// 해당 페이지의 페이지 테이블을 제거하여 나중에 여기에 접근하면
// 페이지 폴트가 나도록 함
pagedir_clear_page(f->t->pagedir, f->upage);
// evict 된 페이지의 물리 주소를 사용하도록 함.
kpage = f->kpage;
#ifdef _LRU_DEBUG_
printf("swap-out %p %d\n", f->upage, list_size(&frame_list));
#endif
}
// 지정된 upage 페이지에 대한 물리 주소를 kpage로 가리키도록 매핑시킴
bool success = pagedir_get_page (t->pagedir, upage) == NULL
&& pagedir_set_page (t->pagedir, upage, kpage, writable);
// 필요한 경우 disk에 저장된 페이지 내용을 불러옴
if (success && do_load){
bool page_writable = p->writable;
success = swap_in_page(p);
if (success && page_writable != writable){
// swap된걸 불러오는 경우 writable 옵션은 저장된 옵션 값을 따른다.
writable = page_writable;
// 해당 writable 값을 사용하기 위해 페이지 테이블을 새로 설정한다.
pagedir_clear_page(t->pagedir, upage);
pagedir_set_page (t->pagedir, upage, kpage, writable);
}
// swap 되어있던걸 읽었으므로 현재 상태는 disk와 동일하기 때문에
// dirty bit를 false로 해준다.
if (success) pagedir_set_dirty(t->pagedir, upage, false);
}
#ifdef _LRU_DEBUG_
if (do_load){
printf("swap-in %p %d %d\n", upage, list_size(&frame_list), writable);
} else {
printf("allocate %p %d %d\n", upage, list_size(&frame_list), writable);
}
#endif
if (success){
if (f == NULL){
// frame 생성해서 list에 추가
// (evict 했다면 그냥 그거에 덮어씀)
f = malloc(sizeof(struct frame));
list_push_back(&frame_list, &f->elem);
}
// 프레임의 내용을 기록함.
f->t = t;
f->upage = upage;
f->kpage = kpage;
f->writable = writable;
} else {
if (kpage != NULL) palloc_free_page (kpage);
if (f != NULL){
list_remove(&f->elem);
free(f);
}
}
return success;
}
void frame_release(struct thread* t){
// frame list 를 돌면서 이 thread에 대한 프레임들이 있으면
// list에서 제거하고 페이지도 free시킨다.
struct frame* f;
struct list_elem *e = list_begin(&frame_list);
while (e != list_end(&frame_list)){
struct list_elem *next = list_next(e);
f = list_entry (e, struct frame, elem);
if (f->t == t){
// candidate가 제거되는 경우, 새로 찾도록 NULL로 표시한다.
if (candidate == f) candidate = NULL;
// 해당 프레임의 페이지 테이블을 제거한다.
pagedir_clear_page(f->t->pagedir, f->upage);
// 할당되어 있던 물리 페이지를 해제한다.
palloc_free_page(f->kpage);
// 해당 프레임을 제거하고 해제한다.
list_remove(&f->elem);
free(f);
}
e = next;
}
// disk에 swap된 정보들도 제거하도록 한다.
swap_release_pages(t);
}
// evict할 frame을 고른다. candidate는 다음에 다음에 evict할 후보 frame이다.
struct frame* pick_evict_frame()
{
struct list_elem *e;
struct frame* to_evict;
if(candidate == NULL)
{
e = list_front(&frame_list);
candidate = list_entry(e, struct frame, elem);
} // 만약 후보 frame이 없다면 (최초의 eviction) frame list의 가장 처음 원소를 잡는다.
e = &candidate->elem;
while(pagedir_is_accessed(candidate->t->pagedir, candidate->upage))
{
pagedir_set_accessed (candidate->t->pagedir, candidate->upage, false);
e = list_clock_next(e, &frame_list); // frame_list의 마지막 원소까지 돌면 처음으로 돌아간다.
candidate = list_entry(e, struct frame, elem);
} // 만일 후보 frame이 access 된 적 있는 frame이라면 access bit를 false 로 바꾸고 다음 frame을 가리키도록 한다.
to_evict = candidate; // 최초로 access 된적 없는 frame을 발견하면 evict할 frame으로 선택한다.
e = list_clock_next(e, &frame_list); // 후보 frame은 evict할 frame의 다음 frame을 가리키도록 한다.
candidate = list_entry(e, struct frame, elem);
return to_evict; // access 안 된 frame이 등장하면 eviction victim으로 선정.
}
| 10cm | trunk/10cm/pintos/src/vm/frame.c | C | oos | 5,625 |
include ../Makefile.kernel
| 10cm | trunk/10cm/pintos/src/vm/Makefile | Makefile | oos | 27 |
/* This file is derived from source code used in MIT's 6.828
course. The original copyright notice is reproduced in full
below. */
/*
* Copyright (C) 1997 Massachusetts Institute of Technology
*
* This software is being provided by the copyright holders under the
* following license. By obtaining, using and/or copying this software,
* you agree that you have read, understood, and will comply with the
* following terms and conditions:
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose and without fee or royalty is
* hereby granted, provided that the full text of this NOTICE appears on
* ALL copies of the software and documentation or portions thereof,
* including modifications, that you make.
*
* THIS SOFTWARE IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO
* REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
* BUT NOT LIMITATION, COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR
* WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR
* THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY
* THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. COPYRIGHT
* HOLDERS WILL BEAR NO LIABILITY FOR ANY USE OF THIS SOFTWARE OR
* DOCUMENTATION.
*
* The name and trademarks of copyright holders may NOT be used in
* advertising or publicity pertaining to the software without specific,
* written prior permission. Title to copyright in this software and any
* associated documentation will at all times remain with copyright
* holders. See the file AUTHORS which should have accompanied this software
* for a list of all copyright holders.
*
* This file may be derived from previously copyrighted software. This
* copyright applies only to those changes made by the copyright
* holders listed in the AUTHORS file. The rest of this file is covered by
* the copyright notices, if any, listed below.
*/
#include "threads/loader.h"
#### Kernel loader.
#### This code should be stored in the first sector of the hard disk.
#### When the BIOS runs, it loads this code at physical address
#### 0x7c00-0x7e00 (512 bytes). Then it jumps to the beginning of it,
#### in real mode. This code switches into protected mode (32-bit
#### mode) so that all of memory can accessed, loads the kernel into
#### memory, and jumps to the first byte of the kernel, where start.S
#### is linked.
/* Flags in control register 0. */
#define CR0_PE 0x00000001 /* Protection Enable. */
#define CR0_EM 0x00000004 /* (Floating-point) Emulation. */
#define CR0_PG 0x80000000 /* Paging. */
#define CR0_WP 0x00010000 /* Write-Protect enable in kernel mode. */
.globl start
start:
# Code runs in real mode, which is a 16-bit segment.
.code16
# Disable interrupts, because we will not be prepared to handle them
# in protected mode until much later.
# String instructions go upward (e.g. for "rep stosl" below).
cli
cld
# Set up data segments.
subw %ax, %ax
movw %ax, %es
movw %ax, %ds
# Set up stack segment.
# Stack grows downward starting from us.
# We don't ever use the stack, but we call into the BIOS,
# which might.
movw %ax, %ss
movw $0x7c00, %sp
#### Enable A20. Address line 20 is tied to low when the machine
#### boots, which prevents addressing memory about 1 MB. This code
#### fixes it.
# Poll status register while busy.
1: inb $0x64, %al
testb $0x2, %al
jnz 1b
# Send command for writing output port.
movb $0xd1, %al
outb %al, $0x64
# Poll status register while busy.
1: inb $0x64, %al
testb $0x2, %al
jnz 1b
# Enable A20 line.
movb $0xdf, %al
outb %al, $0x60
#### Get memory size, via interrupt 15h function 88h. Returns CF
#### clear if successful, with AX = (kB of physical memory) - 1024.
#### This only works for memory sizes <= 65 MB, which should be fine
#### for our purposes. We cap memory at 64 MB because that's all we
#### prepare page tables for, below.
movb $0x88, %ah
int $0x15
jc panic
cli # BIOS might have enabled interrupts
addl $1024, %eax # Total kB memory
cmp $0x10000, %eax # Cap at 64 MB
jbe 1f
mov $0x10000, %eax
1: shrl $2, %eax # Total 4 kB pages
movl %eax, ram_pgs
#### Create temporary page directory and page table and set page
#### directory base register.
# Create page directory at 64 kB and fill with zeroes.
mov $0x1000, %ax
mov %ax, %es
subl %eax, %eax
subl %edi, %edi
movl $0x400, %ecx
rep stosl
# Add PDEs to point to PTEs for the first 64 MB of RAM.
# Also add identical PDEs starting at LOADER_PHYS_BASE.
# See [IA32-v3a] section 3.7.6 "Page-Directory and Page-Table Entries"
# for a description of the bits in %eax.
movl $0x11007, %eax
movl $0x11, %ecx
subl %edi, %edi
1: movl %eax, %es:(%di)
movl %eax, %es:LOADER_PHYS_BASE >> 20(%di)
addw $4, %di
addl $0x1000, %eax
loop 1b
# Set up one-to-map linear to physical map for the first 64 MB of RAM.
# See [IA32-v3a] section 3.7.6 "Page-Directory and Page-Table Entries"
# for a description of the bits in %eax.
movw $0x1100, %ax
movw %ax, %es
movl $0x7, %eax
movl $0x4000, %ecx
subl %edi, %edi
1: movl %eax, %es:(%di)
addw $4, %di
addl $0x1000, %eax
loop 1b
# Set page directory base register.
movl $0x10000, %eax
movl %eax, %cr3
#### Switch to protected mode.
# Note that interrupts are still off.
# Point the GDTR to our GDT. Protected mode requires a GDT.
# We need a data32 prefix to ensure that all 32 bits of the GDT
# descriptor are loaded (default is to load only 24 bits).
data32 lgdt gdtdesc
# Then we turn on the following bits in CR0:
# PE (Protect Enable): this turns on protected mode.
# PG (Paging): turns on paging.
# WP (Write Protect): if unset, ring 0 code ignores
# write-protect bits in page tables (!).
# EM (Emulation): forces floating-point instructions to trap.
# We don't support floating point.
movl %cr0, %eax
orl $CR0_PE | CR0_PG | CR0_WP | CR0_EM, %eax
movl %eax, %cr0
# We're now in protected mode in a 16-bit segment. The CPU still has
# the real-mode code segment cached in %cs's segment descriptor. We
# need to reload %cs, and the easiest way is to use a far jump.
# Because we're not in a 32-bit segment the data32 prefix is needed to
# jump to a 32-bit offset.
data32 ljmp $SEL_KCSEG, $1f + LOADER_PHYS_BASE
# We're now in protected mode in a 32-bit segment.
.code32
# Reload all the other segment registers and the stack pointer to
# point into our new GDT.
1: movw $SEL_KDSEG, %ax
movw %ax, %ds
movw %ax, %es
movw %ax, %fs
movw %ax, %gs
movw %ax, %ss
movl $LOADER_PHYS_BASE + 0x30000, %esp
#### Load kernel starting at physical address LOADER_KERN_BASE by
#### frobbing the IDE controller directly.
movl $1, %ebx
movl $LOADER_KERN_BASE + LOADER_PHYS_BASE, %edi
# Disable interrupt delivery by IDE controller, because we will be
# polling for data.
# (If we don't do this, Bochs 2.2.6 will never deliver any IDE
# interrupt to us later after we reset the interrupt controller during
# boot, even if we also reset the IDE controller.)
movw $0x3f6, %dx
movb $0x02, %al
outb %al, %dx
read_sector:
# Poll status register while controller busy.
movl $0x1f7, %edx
1: inb %dx, %al
testb $0x80, %al
jnz 1b
# Read a single sector.
movl $0x1f2, %edx
movb $1, %al
outb %al, %dx
# Sector number to write in low 28 bits.
# LBA mode, device 0 in top 4 bits.
movl %ebx, %eax
andl $0x0fffffff, %eax
orl $0xe0000000, %eax
# Dump %eax to ports 0x1f3...0x1f6.
movl $4, %ecx
1: incw %dx
outb %al, %dx
shrl $8, %eax
loop 1b
# READ command to command register.
incw %dx
movb $0x20, %al
outb %al, %dx
# Poll status register while controller busy.
1: inb %dx, %al
testb $0x80, %al
jnz 1b
# Poll status register until data ready.
1: inb %dx, %al
testb $0x08, %al
jz 1b
# Transfer sector.
movl $256, %ecx
movl $0x1f0, %edx
rep insw
# Next sector.
incl %ebx
cmpl $KERNEL_LOAD_PAGES*8 + 1, %ebx
jnz read_sector
#### Jump to kernel entry point.
movl $LOADER_PHYS_BASE + LOADER_KERN_BASE, %eax
call *%eax
jmp panic
#### GDT
gdt:
.quad 0x0000000000000000 # null seg
.quad 0x00cf9a000000ffff # code seg
.quad 0x00cf92000000ffff # data seg
gdtdesc:
.word 0x17 # sizeof (gdt) - 1
.long gdt + LOADER_PHYS_BASE # address gdt
#### Fatal error.
#### Print panic_message (with help from the BIOS) and spin.
panic: .code16 # We only panic in real mode.
movw $panic_message, %si
movb $0xe, %ah
subb %bh, %bh
1: lodsb
test %al, %al
2: jz 2b # Spin.
int $0x10
jmp 1b
panic_message:
.ascii "Panic!"
.byte 0
#### Physical memory size in 4 kB pages.
#### This is initialized by the loader and read by the kernel.
.org LOADER_RAM_PGS - LOADER_BASE
ram_pgs:
.long 0
#### Command-line arguments and their count.
#### This is written by the `pintos' utility and read by the kernel.
#### The loader itself does not do anything with the command line.
.org LOADER_ARG_CNT - LOADER_BASE
arg_cnt:
.long 0
.org LOADER_ARGS - LOADER_BASE
args:
.fill 0x80, 1, 0
#### Boot-sector signature.
#### The BIOS checks that this is set properly.
.org LOADER_SIG - LOADER_BASE
.word 0xaa55
| 10cm | trunk/10cm/pintos/src/threads/loader.S | Unix Assembly | oos | 9,186 |
#ifndef THREADS_LOADER_H
#define THREADS_LOADER_H
/* Constants fixed by the PC BIOS. */
#define LOADER_BASE 0x7c00 /* Physical address of loader's base. */
#define LOADER_END 0x7e00 /* Physical address of end of loader. */
/* Physical address of kernel base. */
#define LOADER_KERN_BASE 0x100000 /* 1 MB. */
/* Kernel virtual address at which all physical memory is mapped.
The loader maps the 4 MB at the bottom of physical memory to
this virtual base address. Later, paging_init() adds the rest
of physical memory to the mapping.
This must be aligned on a 4 MB boundary. */
#define LOADER_PHYS_BASE 0xc0000000 /* 3 GB. */
/* Important loader physical addresses. */
#define LOADER_SIG (LOADER_END - LOADER_SIG_LEN) /* 0xaa55 BIOS signature. */
#define LOADER_ARGS (LOADER_SIG - LOADER_ARGS_LEN) /* Command-line args. */
#define LOADER_ARG_CNT (LOADER_ARGS - LOADER_ARG_CNT_LEN) /* Number of args. */
#define LOADER_RAM_PGS (LOADER_ARG_CNT - LOADER_RAM_PGS_LEN) /* # RAM pages. */
/* Sizes of loader data structures. */
#define LOADER_SIG_LEN 2
#define LOADER_ARGS_LEN 128
#define LOADER_ARG_CNT_LEN 4
#define LOADER_RAM_PGS_LEN 4
/* GDT selectors defined by loader.
More selectors are defined by userprog/gdt.h. */
#define SEL_NULL 0x00 /* Null selector. */
#define SEL_KCSEG 0x08 /* Kernel code selector. */
#define SEL_KDSEG 0x10 /* Kernel data selector. */
#endif /* threads/loader.h */
| 10cm | trunk/10cm/pintos/src/threads/loader.h | C | oos | 1,471 |
#include "threads/switch.h"
#### struct thread *switch_threads (struct thread *cur, struct thread *next);
####
#### Switches from CUR, which must be the running thread, to NEXT,
#### which must also be running switch_threads(), returning CUR in
#### NEXT's context.
####
#### This function works by assuming that the thread we're switching
#### into is also running switch_threads(). Thus, all it has to do is
#### preserve a few registers on the stack, then switch stacks and
#### restore the registers. As part of switching stacks we record the
#### current stack pointer in CUR's thread structure.
.globl switch_threads
.func switch_threads
switch_threads:
# Save caller's register state.
#
# Note that the SVR4 ABI allows you to destroy %eax, %ecx, %edx,
# but requires us to preserve %ebx, %ebp, %esi, %edi. See
# [SysV-ABI-386] pages 3-11 and 3-12 for details.
#
# This stack frame must match the one set up by thread_create()
# in size.
pushl %ebx
pushl %ebp
pushl %esi
pushl %edi
# Get offsetof (struct thread, stack).
.globl thread_stack_ofs
mov thread_stack_ofs, %edx
# Save current stack pointer to old thread's stack, if any.
movl SWITCH_CUR(%esp), %eax
movl %esp, (%eax,%edx,1)
# Restore stack pointer from new thread's stack.
movl SWITCH_NEXT(%esp), %ecx
movl (%ecx,%edx,1), %esp
# Restore caller's register state.
popl %edi
popl %esi
popl %ebp
popl %ebx
ret
.endfunc
.globl switch_entry
.func switch_entry
switch_entry:
# Discard switch_threads() arguments.
addl $8, %esp
# Call schedule_tail(prev).
pushl %eax
.globl schedule_tail
call schedule_tail
addl $4, %esp
# Start thread proper.
ret
.endfunc
| 10cm | trunk/10cm/pintos/src/threads/switch.S | Unix Assembly | oos | 1,669 |
#ifndef THREADS_THREAD_H
#define THREADS_THREAD_H
#include <debug.h>
#include <list.h>
#include <stdint.h>
/* States in a thread's life cycle. */
enum thread_status
{
THREAD_RUNNING, /* Running thread. */
THREAD_READY, /* Not running but ready to run. */
THREAD_BLOCKED, /* Waiting for an event to trigger. */
THREAD_DYING /* About to be destroyed. */
};
/* Thread identifier type.
You can redefine this to whatever type you likes. */
typedef int tid_t;
#define TID_ERROR ((tid_t) -1) /* Error value for tid_t. */
/* Thread priorities. */
#define PRI_MIN 0 /* Lowest priority. */
#define PRI_DEFAULT 31 /* Default priority. */
#define PRI_MAX 63 /* Highest priority. */
/* A kernel thread or user process.
Each thread structure is stored in its own 4 kB page. The
thread structure itself sits at the very bottom of the page
(at offset 0). The rest of the page is reserved for the
thread's kernel stack, which grows downward from the top of
the page (at offset 4 kB). Here's an illustration:
4 kB +---------------------------------+
| kernel stack |
| | |
| | |
| V |
| grows downward |
| |
| |
| |
| |
| |
| |
| |
| |
+---------------------------------+
| magic |
| : |
| : |
| name |
| status |
0 kB +---------------------------------+
The upshot of this is twofold:
1. First, `struct thread' must not be allowed to grow too
big. If it does, then there will not be enough room for
the kernel stack. Our base `struct thread' is only a
few bytes in size. It probably should stay well under 1
kB.
2. Second, kernel stacks must not be allowed to grow too
large. If a stack overflows, it will corrupt the thread
state. Thus, kernel functions should not allocate large
structures or arrays as non-static local variables. Use
dynamic allocation with malloc() or palloc_get_page()
instead.
The first symptom of either of these problems will probably be
an assertion failure in thread_current(), which checks that
the `magic' member of the running thread's `struct thread' is
set to THREAD_MAGIC. Stack overflow will normally change this
value, triggering the assertion. */
/* The `elem' member has a dual purpose. It can be an element in
the run queue (thread.c), or it can be an element in a
semaphore wait list (synch.c). It can be used these two ways
only because they are mutually exclusive: only a thread in the
ready state is on the run queue, whereas only a thread in the
blocked state is on a semaphore wait list. */
struct thread
{
/* Owned by thread.c. */
tid_t tid; /* Thread identifier. */
enum thread_status status; /* Thread state. */
char name[16]; /* Name (for debugging purposes). */
uint8_t *stack; /* Saved stack pointer. */
int priority; /* Priority. */
struct list_elem allelem; /* List element for all threads list. */
/* Shared between thread.c and synch.c. */
struct list_elem elem; /* List element. */
#ifdef USERPROG
/* Owned by userprog/process.c. */
uint32_t *pagedir; /* Page directory. */
struct list fd_list;
struct file* code_file;
void *low_esp;
#endif
/* Owned by thread.c. */
unsigned magic; /* Detects stack overflow. */
unsigned remain_tick; /* Remanning tick count. */
};
// file descriptor for user program
typedef struct _fd_element {
struct file* file;
int fd_number;
struct list_elem elem;
} fd_element;
/* If false (default), use round-robin scheduler.
If true, use multi-level feedback queue scheduler.
Controlled by kernel command-line option "-o mlfqs". */
extern bool thread_mlfqs;
#define MAX_PRIO 64
typedef struct _prio_array {
int nr_active; // The number of tasks
int highest_prio;
unsigned long bitmap[MAX_PRIO];
struct list queue[MAX_PRIO];
} prio_array;
typedef struct _runqueue {
prio_array *active; // scheduling target tasks
prio_array *expired;
prio_array arrays[2];
} runqueue;
void add_block_list(int64_t, int64_t );
void check_list(struct list *to_check_list);
void add_thread_to_prio_array(prio_array *arr, struct thread* t);
struct thread* dequeue_thread_from_prio_array(prio_array *arr);
void swap_active_to_expired(void);
void thread_init (void);
void thread_start (void);
void thread_tick (void);
void thread_print_stats (void);
typedef void thread_func (void *aux);
tid_t thread_create (const char *name, int priority, thread_func *, void *);
void thread_block (void);
void thread_unblock (struct thread *);
struct thread *thread_current (void);
tid_t thread_tid (void);
const char *thread_name (void);
void thread_exit (void) NO_RETURN;
void thread_yield (void);
/* Performs some operation on thread t, given auxiliary data AUX. */
typedef void thread_action_func (struct thread *t, void *aux);
void thread_foreach (thread_action_func *, void *);
int thread_get_priority (void);
void thread_set_priority (int);
int thread_get_nice (void);
void thread_set_nice (int);
int thread_get_recent_cpu (void);
int thread_get_load_avg (void);
#endif /* threads/thread.h */
| 10cm | trunk/10cm/pintos/src/threads/thread.h | C | oos | 6,162 |
#ifndef THREADS_SYNCH_H
#define THREADS_SYNCH_H
#include <list.h>
#include <stdbool.h>
/* A counting semaphore. */
struct semaphore
{
unsigned value; /* Current value. */
struct list waiters; /* List of waiting threads. */
};
void sema_init (struct semaphore *, unsigned value);
void sema_down (struct semaphore *);
bool sema_try_down (struct semaphore *);
void sema_up (struct semaphore *);
void sema_self_test (void);
/* Lock. */
struct lock
{
struct thread *holder; /* Thread holding lock (for debugging). */
struct semaphore semaphore; /* Binary semaphore controlling access. */
};
void lock_init (struct lock *);
void lock_acquire (struct lock *);
bool lock_try_acquire (struct lock *);
void lock_release (struct lock *);
bool lock_held_by_current_thread (const struct lock *);
/* A condition variable. */
struct condition
{
struct list waiters; /* List of waiting threads. */
};
void cond_init (struct condition *);
void cond_wait (struct condition *, struct lock *);
void cond_signal (struct condition *, struct lock *);
void cond_broadcast (struct condition *, struct lock *);
/* Optimization barrier.
The compiler will not reorder operations across an
optimization barrier. See "Optimization Barriers" in the
reference guide for more information.*/
#define barrier() asm volatile ("" : : : "memory")
#endif /* threads/synch.h */
| 10cm | trunk/10cm/pintos/src/threads/synch.h | C | oos | 1,424 |
#include "threads/loader.h"
OUTPUT_FORMAT("elf32-i386")
OUTPUT_ARCH("i386")
ENTRY(start) /* Kernel starts at "start" symbol. */
SECTIONS
{
/* Specifies the virtual address for the kernel base. */
. = LOADER_PHYS_BASE + LOADER_KERN_BASE;
_start = .;
/* Kernel starts with code, followed by read-only data and writable data. */
.text : { *(.start) *(.text) } = 0x90
.rodata : { *(.rodata) *(.rodata.*)
. = ALIGN(0x1000);
_end_kernel_text = .; }
.data : { *(.data) }
/* BSS (zero-initialized data) is after everything else. */
_start_bss = .;
.bss : { *(.bss) }
_end_bss = .;
_end = .;
}
| 10cm | trunk/10cm/pintos/src/threads/kernel.lds.S | Unix Assembly | oos | 632 |
#ifndef THREADS_SWITCH_H
#define THREADS_SWITCH_H
#ifndef __ASSEMBLER__
/* switch_thread()'s stack frame. */
struct switch_threads_frame
{
uint32_t edi; /* 0: Saved %edi. */
uint32_t esi; /* 4: Saved %esi. */
uint32_t ebp; /* 8: Saved %ebp. */
uint32_t ebx; /* 12: Saved %ebx. */
void (*eip) (void); /* 16: Return address. */
struct thread *cur; /* 20: switch_threads()'s CUR argument. */
struct thread *next; /* 24: switch_threads()'s NEXT argument. */
};
/* Switches from CUR, which must be the running thread, to NEXT,
which must also be running switch_threads(), and returning CUR in
NEXT's context. */
struct thread *switch_threads (struct thread *cur, struct thread *next);
/* Stack frame for switch_entry(). */
struct switch_entry_frame
{
void (*eip) (void);
};
void switch_entry (void);
/* Pops the CUR and NEXT arguments off the stack, for use in
initializing threads. */
void switch_thunk (void);
#endif
/* Offsets used by switch.S. */
#define SWITCH_CUR 20
#define SWITCH_NEXT 24
#endif /* threads/switch.h */
| 10cm | trunk/10cm/pintos/src/threads/switch.h | C | oos | 1,169 |
#include "threads/thread.h"
#include <debug.h>
#include <stddef.h>
#include <random.h>
#include <stdio.h>
#include <string.h>
#include "threads/flags.h"
#include "threads/interrupt.h"
#include "threads/intr-stubs.h"
#include "threads/palloc.h"
#include "threads/switch.h"
#include "threads/synch.h"
#include "threads/vaddr.h"
#include "devices/timer.h"
#ifdef USERPROG
#include "userprog/process.h"
#endif
/* Random value for struct thread's `magic' member.
Used to detect stack overflow. See the big comment at the top
of thread.h for details. */
#define THREAD_MAGIC 0xcd6abf4b
/* Area I added */
static bool is_thread (struct thread *) UNUSED;
/*
List of processes in THREAD_BLOCKED state.
These processes are to wait until the given
time slices expired
*/
static struct list block_list;
/* struct node for manipulating block_list
*/
typedef struct blocked_node
{
struct list_elem elem;
int64_t start;
int64_t ticks;
struct thread* blocked;
} bnode;
/* add a thread into the block list. This function insert
the thread with an nondescending order in the view of
remaining time until when the thread wakes up.
*/
void
add_block_list(int64_t start, int64_t ticks)
{
struct thread *cur = thread_current();
bnode new_block;
new_block.start = start;
new_block.ticks = ticks;
new_block.blocked = cur;
enum intr_level old_level;
ASSERT (!intr_context());
// interrupt should be off before the thread_block() function called.
old_level = intr_disable ();
struct list_elem *e;
for ( e = list_begin (&block_list); e!= list_end(&block_list); e = list_next(e) )
{
bnode *head_node = list_entry ( e, bnode, elem );
int64_t time = head_node->start + head_node->ticks;
if (time == start+ticks){
if (cur->priority >= head_node->blocked->priority){
break;
}
} else if( time > start+ticks){
break;
}
}
list_insert ( e, &new_block.elem );
thread_block();
intr_set_level (old_level);
}
void check_list(struct list *to_check_list)
{
struct list_elem *e;
// if the list is empty, do nothing.
while ( !list_empty(to_check_list) )
{
e = list_begin(to_check_list);
bnode * bnode_p = list_entry ( e, bnode, elem );
if ( timer_elapsed(bnode_p->start) >= bnode_p -> ticks )
{
thread_unblock(bnode_p->blocked);
list_pop_front (to_check_list);
} else {
break;
}
}
}
static runqueue ready_queue;
static int is_preemted;
void add_thread_to_prio_array(prio_array *arr, struct thread* t){
arr->nr_active++;
arr->bitmap[t->priority] = 1;
list_push_back (&arr->queue[t->priority], &t->elem);
t->status = THREAD_READY;
if (t->priority > arr->highest_prio) arr->highest_prio = t->priority;
}
struct thread* dequeue_thread_from_prio_array(prio_array *arr){
int i;
for (i = arr->highest_prio; i >= 0; i--) {
if (arr->bitmap[i] > 0) break;
}
struct thread* t = list_entry (list_pop_front (&arr->queue[i]), struct thread, elem);
if (list_empty(&arr->queue[i])){
arr->bitmap[i] = 0;
}
arr->nr_active--;
arr->highest_prio = i;
return t;
}
void swap_active_to_expired(){
prio_array* temp = ready_queue.active;
ready_queue.active = ready_queue.expired;
ready_queue.expired = temp;
}
/* List of processes in THREAD_READY state, that is, processes
that are ready to run but not actually running. */
//static struct list ready_list;
/* List of all processes. Processes are added to this list
when they are first scheduled and removed when they exit. */
static struct list all_list;
/* Idle thread. */
static struct thread *idle_thread;
/* Initial thread, the thread running init.c:main(). */
static struct thread *initial_thread;
/* Lock used by allocate_tid(). */
static struct lock tid_lock;
/* Stack frame for kernel_thread() */
struct kernel_thread_frame
{
void *eip; /* Return address. */
thread_func *function; /* Function to call. */
void *aux; /* Auxiliary data for function. */
};
/* Statistics. */
static long long idle_ticks; /* # of timer ticks spent idle. */
static long long kernel_ticks; /* # of timer ticks in kernel threads. */
static long long user_ticks; /* # of timer ticks in user programs. */
/* Scheduling. */
#define TIME_SLICE 4 /* # of timer ticks to give each thread. */
static unsigned thread_ticks; /* # of timer ticks since last yield. */
/* If false (default), use round-robin scheduler.
If true, use multi-level feedback queue scheduler.
Controlled by kernel command-line option "-o mlfqs". */
bool thread_mlfqs;
static void kernel_thread (thread_func *, void *aux);
static void idle (void *aux UNUSED);
static struct thread *running_thread (void);
static struct thread *next_thread_to_run (void);
static void init_thread (struct thread *, const char *name, int priority);
//static bool is_thread (struct thread *) UNUSED;
static void *alloc_frame (struct thread *, size_t size);
static void schedule (void);
void schedule_tail (struct thread *prev);
static tid_t allocate_tid (void);
/* Initializes the threading system by transforming the code
that's currently running into a thread. This cannot work in
general and it is possible in this case only because loader.S
was careful to put the bottom of the stack at a page boundary.
Also initializes the run queue and the tid lock.
After calling this function, be sure to initialize the page
allocator before trying to create any threads with
thread_create().
It is not safe to call thread_current() until this function
finishes. */
void
thread_init (void)
{
ASSERT (intr_get_level () == INTR_OFF);
lock_init (&tid_lock);
// list_init (&ready_list);
list_init (&all_list);
list_init (&block_list);
ready_queue.active = &ready_queue.arrays[0];
ready_queue.expired = &ready_queue.arrays[1];
int i;
for (i=0;i<MAX_PRIO;i++){
list_init(&ready_queue.active->queue[i]);
list_init(&ready_queue.expired->queue[i]);
}
/* Set up a thread structure for the running thread. */
initial_thread = running_thread ();
init_thread (initial_thread, "main", PRI_DEFAULT);
initial_thread->status = THREAD_RUNNING;
initial_thread->tid = allocate_tid ();
}
/* Starts preemptive thread scheduling by enabling interrupts.
Also creates the idle thread. */
void
thread_start (void)
{
/* Create the idle thread. */
struct semaphore idle_started;
sema_init (&idle_started, 0);
thread_create ("idle", PRI_MIN, idle, &idle_started);
/* Start preemptive thread scheduling. */
intr_enable ();
/* Wait for the idle thread to initialize idle_thread. */
sema_down (&idle_started);
}
/* Called by the timer interrupt handler at each timer tick.
Thus, this function runs in an external interrupt context. */
void
thread_tick (void)
{
struct thread *t = thread_current ();
/* Update statistics. */
if (t == idle_thread)
idle_ticks++;
#ifdef USERPROG
else if (t->pagedir != NULL)
user_ticks++;
#endif
else
kernel_ticks++;
check_list(&block_list);
/* Enforce preemption. */
thread_ticks++;
if (is_preemted){
is_preemted = 0;
t->remain_tick -= thread_ticks;
intr_yield_on_return ();
} else if (thread_ticks >= t->remain_tick){
t->remain_tick = 0;
intr_yield_on_return ();
}
}
/* Prints thread statistics. */
void
thread_print_stats (void)
{
printf ("Thread: %lld idle ticks, %lld kernel ticks, %lld user ticks\n",
idle_ticks, kernel_ticks, user_ticks);
}
/* Creates a new kernel thread named NAME with the given initial
PRIORITY, which executes FUNCTION passing AUX as the argument,
and adds it to the ready queue. Returns the thread identifier
for the new thread, or TID_ERROR if creation fails.
If thread_start() has been called, then the new thread may be
scheduled before thread_create() returns. It could even exit
before thread_create() returns. Contrariwise, the original
thread may run for any amount of time before the new thread is
scheduled. Use a semaphore or some other form of
synchronization if you need to ensure ordering.
The code provided sets the new thread's "priority" member to
PRIORITY, but no actual priority scheduling is implemented.
Priority scheduling is the goal of Problem 1-3. */
tid_t
thread_create (const char *name, int priority,
thread_func *function, void *aux)
{
struct thread *t;
struct kernel_thread_frame *kf;
struct switch_entry_frame *ef;
struct switch_threads_frame *sf;
tid_t tid;
enum intr_level old_level;
ASSERT (function != NULL);
/* Allocate thread. */
t = palloc_get_page (PAL_ZERO);
if (t == NULL)
return TID_ERROR;
/* Initialize thread. */
init_thread (t, name, priority);
tid = t->tid = allocate_tid ();
/* Prepare thread for first run by initializing its stack.
Do this atomically so intermediate values for the "stack"
member cannot be observed. */
old_level = intr_disable ();
/* Stack frame for kernel_thread(). */
kf = alloc_frame (t, sizeof *kf);
kf->eip = NULL;
kf->function = function;
kf->aux = aux;
/* Stack frame for switch_entry(). */
ef = alloc_frame (t, sizeof *ef);
ef->eip = (void (*) (void)) kernel_thread;
/* Stack frame for switch_threads(). */
sf = alloc_frame (t, sizeof *sf);
sf->eip = switch_entry;
sf->ebp = 0;
list_init(&t->fd_list);
intr_set_level (old_level);
/* Add to run queue. */
thread_unblock (t);
return tid;
}
/* Puts the current thread to sleep. It will not be scheduled
again until awoken by thread_unblock()
This function must be called with interrupts turned off. It
is usually a better idea to use one of the synchronization
primitives in synch.h. */
void
thread_block (void)
{
ASSERT (!intr_context ());
ASSERT (intr_get_level () == INTR_OFF);
thread_current ()->status = THREAD_BLOCKED;
schedule ();
}
/* Transitions a blocked thread T to the ready-to-run state.
This is an error if T is not blocked. (Use thread_yield() to
make the running thread ready.)
This function does not preempt the running thread. This can
be important: if the caller had disabled interrupts itself,
it may expect that it can atomically unblock a thread and
update other data. */
void
thread_unblock (struct thread *t)
{
struct thread *cur = thread_current();
enum intr_level old_level;
ASSERT (is_thread (t));
old_level = intr_disable ();
ASSERT (t->status == THREAD_BLOCKED);
add_thread_to_prio_array(ready_queue.active, t);
t->remain_tick = t->priority+5;
// list_push_back (&ready_list, &t->elem);
// t->status = THREAD_READY;
intr_set_level (old_level);
if (cur != idle_thread){
if (cur->priority < t->priority){
is_preemted = 1;
}
}
}
/* Returns the name of the running thread. */
const char *
thread_name (void)
{
return thread_current ()->name;
}
/* Returns the running thread.
This is running_thread() plus a couple of sanity checks.
See the big comment at the top of thread.h for details. */
struct thread *
thread_current (void)
{
struct thread *t = running_thread ();
/* Make sure T is really a thread.
If either of these assertions fire, then your thread may
have overflowed its stack. Each thread has less than 4kB
of stack, so a few big automatic arrays or moderate
recursion can cause stack overflow. */
ASSERT (is_thread (t));
ASSERT (t->status == THREAD_RUNNING);
return t;
}
/* Returns the running thread's tid. */
tid_t
thread_tid (void)
{
return thread_current ()->tid;
}
/* Deschedules the current thread and destroys it. Never
returns to the caller. */
void
thread_exit (void)
{
ASSERT (!intr_context ());
#ifdef USERPROG
process_exit ();
#endif
/* Remove thread from all threads list, set our status to dying,
and schedule another process. That process will destroy us
when it call schedule_tail(). */
intr_disable ();
list_remove (&thread_current()->allelem);
thread_current ()->status = THREAD_DYING;
schedule ();
NOT_REACHED ();
}
/* Yields the CPU. The current thread is not put to sled_exit (void)
361 thread_exit (void)
ep and
may be scheduled again immediately at the scheduler's whim. */
void
thread_yield (void)
{
struct thread *cur = thread_current ();
enum intr_level old_level;
ASSERT (!intr_context ());
old_level = intr_disable ();
if (cur != idle_thread){
if (cur->remain_tick > 0){
add_thread_to_prio_array(ready_queue.active, cur);
} else {
cur->remain_tick = cur->priority + 5;
add_thread_to_prio_array(ready_queue.expired, cur);
}
}
// list_push_back (&ready_list, &cur->elem);
cur->status = THREAD_READY;
schedule ();
intr_set_level (old_level);
}
/* Invoke function "func" on all threads, passing along "aux".
This function must be called with interrupts off. */
void
thread_foreach (thread_action_func *func, void *aux)
{
struct list_elem *e;
ASSERT (intr_get_level () == INTR_OFF);
for (e = list_begin (&all_list); e != list_end (&all_list);
e = list_next (e))
{
struct thread *t = list_entry (e, struct thread, allelem);
func (t, aux);
}
}
/* Sets the current thread's priority to NEW_PRIORITY. */
void
thread_set_priority (int new_priority)
{
thread_current ()->priority = new_priority;
}
/* Returns the current thread's priority. */
int
thread_get_priority (void)
{
return thread_current ()->priority;
}
/* Sets the current thread's nice value to NICE. */
void
thread_set_nice (int nice UNUSED)
{
/* Not yet implemented. */
}
/* Returns the current thread's nice value. */
int
thread_get_nice (void)
{
/* Not yet implemented. */
return 0;
}
/* Returns 100 times the system load average. */
int
thread_get_load_avg (void)
{
/* Not yet implemented. */
return 0;
}
/* Returns 100 times the current thread's recent_cpu value. */
int
thread_get_recent_cpu (void)
{
/* Not yet implemented. */
return 0;
}
/* Idle thread. Executes when no other thread is ready to run.
The idle thread is initially put on the ready list by
thread_start(). It will be scheduled once initially, at which
point it initializes idle_thread, "up"s the semaphore passed
to it to enable thread_start() to continue and immediately
blocks. After that, the idle thread never appears in the
ready list. It is returned by next_thread_to_run() as a
special case when the ready list is empty. */
static void
idle (void *idle_started_ UNUSED)
{
struct semaphore *idle_started = idle_started_;
idle_thread = thread_current ();
sema_up (idle_started);
for (;;)
{
/* Let someone else run. */
intr_disable ();
thread_block ();
/* Re-enable interrupts and wait for the next one.
The `sti' instruction disables interrupts until the
completion of the next instruction, so these two
instructions are executed atomically. This atomicity is
important; otherwise, an interrupt could be handled
between re-enabling interrupts and waiting for the next
one to occur, wasting as much as one clock tick worth of
time.
See: [IA32-v2a] "HLT", [IA32-v2b] "STI", and [IA32-v3a]
7.11.1 "HLT Instruction". */
asm volatile ("sti; hlt" : : : "memory");
}
}
/* Function used as the basis for a kernel thread. */
static void
kernel_thread (thread_func *function, void *aux)
{
ASSERT (function != NULL);
intr_enable (); /* The scheduler runs with interrupts off. */
function (aux); /* Execute the thread function. */
thread_exit (); /* If function() returns, kill the thread. */
}
/* Returns the running thread. */
struct thread *
running_thread (void)
{
uint32_t *esp;
/* Copy the CPU's stack pointer into `esp', and then round that
down to the start of a page. Because `struct thread' is
always at the beginning of a page and the stack pointer is
somewhere in the middle, this locates the curent thread. */
asm ("mov %%esp, %0" : "=g" (esp));
return pg_round_down (esp);
}
/* Returns true if T appears to point to a valid thread. */
static bool
is_thread (struct thread *t)
{
return t != NULL && t->magic == THREAD_MAGIC;
}
/* Does basic initialization of T as a blocked thread named
NAME. */
static void
init_thread (struct thread *t, const char *name, int priority)
{
ASSERT (t != NULL);
ASSERT (PRI_MIN <= priority && priority <= PRI_MAX);
ASSERT (name != NULL);
memset (t, 0, sizeof *t);
t->status = THREAD_BLOCKED;
strlcpy (t->name, name, sizeof t->name);
t->stack = (uint8_t *) t + PGSIZE;
t->priority = priority;
t->magic = THREAD_MAGIC;
list_push_back (&all_list, &t->allelem);
}
/* Allocates a SIZE-byte frame at the top of thread T's stack and
returns a pointer to the frame's base. */
static void *
alloc_frame (struct thread *t, size_t size)
{
/* Stack data is always allocated in word-size units. */
ASSERT (is_thread (t));
ASSERT (size % sizeof (uint32_t) == 0);
t->stack -= size;
return t->stack;
}
/* Chooses and returns the next thread to be scheduled. Should
return a thread from the run queue, unless the run queue is
empty. (If the running thread can continue running, then it
will be in the run queue) If the run queue is empty, return
idle_thread. */
static struct thread *
next_thread_to_run (void)
{
if (ready_queue.active->nr_active == 0 && ready_queue.expired->nr_active == 0){
// if (list_empty (&ready_list))
return idle_thread;
} else {
if (ready_queue.active->nr_active == 0){
swap_active_to_expired();
}
return dequeue_thread_from_prio_array(ready_queue.active);
//return list_entry (list_pop_front (&ready_list), struct thread, elem);
}
}
/* Completes a thread switch by activating the new thread's page
tables, and, if the previous thread is dying, destroying it.
At this function's invocation, we just switched from thread
PREV, the new thread is already running, and interrupts are
still disabled. This function is normally invoked by
thread_schedule() as its final action before returning, but
the first time a thread is scheduled it is called by
switch_entry() (see switch.S).
It's not safe to call printf() until the thread switch is
complete. In practice that means that printf()s should be
added at the end of the function.
After this function and its caller returns, the thread switch
is complete. */
void
schedule_tail (struct thread *prev)
{
struct thread *cur = running_thread ();
ASSERT (intr_get_level () == INTR_OFF);
/* Mark us as running. */
cur->status = THREAD_RUNNING;
/* Start new time slice. */
thread_ticks = 0;
#ifdef USERPROG
/* Activate the new address space. */
process_activate ();
#endif
/* If the thread we switched from is dying, destroy its struct
thread. This must happen late so that thread_exit() doesn't
pull out the rug under itself. (We do not free
initial_thread because its memory was not obtained via
palloc().) */
if (prev != NULL && prev->status == THREAD_DYING && prev != initial_thread)
{
ASSERT (prev != cur);
palloc_free_page (prev);
}
}
/* Schedules a new process. At entry, interrupts must be off and
the running process's state must have been changed from
running to some other state. This function finds another
thread to run and switches to it.
It's not safe to call printf() until schedule_tail() has
completed. */
static void
schedule (void)
{
struct thread *cur = running_thread ();
struct thread *next = next_thread_to_run ();
struct thread *prev = NULL;
ASSERT (intr_get_level () == INTR_OFF);
ASSERT (cur->status != THREAD_RUNNING);
ASSERT (is_thread (next));
if (cur != next)
prev = switch_threads (cur, next);
schedule_tail (prev);
}
/* Returns a tid to use for a new thread. */
static tid_t
allocate_tid (void)
{
static tid_t next_tid = 1;
tid_t tid;
lock_acquire (&tid_lock);
tid = next_tid++;
lock_release (&tid_lock);
return tid;
}
/* Offset of "stack" member within "struct thread".
Used by switch.S, which can't figure it out on its own. */
uint32_t thread_stack_ofs = offsetof (struct thread, stack);
| 10cm | trunk/10cm/pintos/src/threads/thread.c | C | oos | 20,265 |
# -*- makefile -*-
os.dsk: DEFINES =
KERNEL_SUBDIRS = threads devices lib lib/kernel $(TEST_SUBDIRS)
TEST_SUBDIRS = tests/threads
GRADING_FILE = $(SRCDIR)/tests/threads/Grading
SIMULATOR = --bochs
| 10cm | trunk/10cm/pintos/src/threads/Make.vars | Makefile | oos | 198 |
#ifndef THREADS_FLAGS_H
#define THREADS_FLAGS_H
/* EFLAGS Register. */
#define FLAG_MBS 0x00000002 /* Must be set. */
#define FLAG_IF 0x00000200 /* Interrupt Flag. */
#endif /* threads/flags.h */
| 10cm | trunk/10cm/pintos/src/threads/flags.h | C | oos | 207 |
#include "threads/init.h"
#include <console.h>
#include <debug.h>
#include <limits.h>
#include <random.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "devices/kbd.h"
#include "devices/input.h"
#include "devices/serial.h"
#include "devices/timer.h"
#include "devices/vga.h"
#include "devices/rtc.h"
#include "threads/interrupt.h"
#include "threads/io.h"
#include "threads/loader.h"
#include "threads/malloc.h"
#include "threads/palloc.h"
#include "threads/pte.h"
#include "threads/thread.h"
#ifdef USERPROG
#include "userprog/process.h"
#include "userprog/exception.h"
#include "userprog/gdt.h"
#include "userprog/syscall.h"
#include "userprog/tss.h"
#else
#include "tests/threads/tests.h"
#endif
#ifdef FILESYS
#include "devices/disk.h"
#include "filesys/filesys.h"
#include "filesys/fsutil.h"
#include "filesys/cache.h"
#endif
#include "vm/frame.h"
#include "vm/swap.h"
/* Amount of physical memory, in 4 kB pages. */
size_t ram_pages;
/* Page directory with kernel mappings only. */
uint32_t *base_page_dir;
#ifdef FILESYS
/* -f: Format the file system? */
static bool format_filesys;
#endif
/* -q: Power off after kernel tasks complete? */
bool power_off_when_done;
/* -r: Reboot after kernel tasks complete? */
static bool reboot_when_done;
static void ram_init (void);
static void paging_init (void);
static char **read_command_line (void);
static char **parse_options (char **argv);
static void run_actions (char **argv);
static void usage (void);
static void print_stats (void);
int main (void) NO_RETURN;
/* PintOS main program. */
int
main (void)
{
char **argv;
/* Clear BSS and get machine's RAM size. */
ram_init ();
/* Break command line into arguments and parse options. */
argv = read_command_line ();
argv = parse_options (argv);
/* Initialize ourselves as a thread so we can use locks,
then enable console locking. */
thread_init ();
console_init ();
/* Greet user. */
printf ("Pintos booting with %'zu kB RAM...\n", ram_pages * PGSIZE / 1024);
/* Initialize memory system. */
palloc_init ();
malloc_init ();
paging_init ();
/* Segmentation. */
#ifdef USERPROG
tss_init ();
gdt_init ();
#endif
/* Initialize interrupt handlers. */
intr_init ();
timer_init ();
kbd_init ();
input_init ();
#ifdef USERPROG
exception_init ();
syscall_init ();
frame_init();
#endif
/* Start thread scheduler and enable interrupts. */
thread_start ();
serial_init_queue ();
timer_calibrate ();
#ifdef FILESYS
/* Initialize file system. */
disk_init ();
cache_init();
filesys_init (format_filesys);
#endif
#ifdef USERPROG
swap_init();
#endif
printf ("Boot complete.\n");
/* Run actions specified on kernel command line. */
run_actions (argv);
/* Finish up. */
if (reboot_when_done)
reboot ();
if (power_off_when_done)
power_off ();
thread_exit ();
}
/* Clear BSS and obtain RAM size from loader. */
static void
ram_init (void)
{
/* The "BSS" is a segment that should be initialized to zeros.
It isn't actually stored on disk or zeroed by the kernel
loader, so we have to zero it ourselves.
The start and end of the BSS segment is recorded by the
linker as _start_bss and _end_bss. See kernel.lds. */
extern char _start_bss, _end_bss;
memset (&_start_bss, 0, &_end_bss - &_start_bss);
/* Get RAM size from loader. See loader.S. */
ram_pages = *(uint32_t *) ptov (LOADER_RAM_PGS);
}
/* Populates the base page directory and page table with the
kernel virtual mapping, and then sets up the CPU to use the
new page directory. Points base_page_dir to the page
directory it creates.
At the time this function is called, the active page table
(set up by loader.S) only maps the first 4 MB of RAM, so we
should not try to use extravagant amounts of memory.
Fortunately, there is no need to do so. */
static void
paging_init (void)
{
uint32_t *pd, *pt;
size_t page;
extern char _start, _end_kernel_text;
pd = base_page_dir = palloc_get_page (PAL_ASSERT | PAL_ZERO);
pt = NULL;
for (page = 0; page < ram_pages; page++)
{
uintptr_t paddr = page * PGSIZE;
char *vaddr = ptov (paddr);
size_t pde_idx = pd_no (vaddr);
size_t pte_idx = pt_no (vaddr);
bool in_kernel_text = &_start <= vaddr && vaddr < &_end_kernel_text;
if (pd[pde_idx] == 0)
{
pt = palloc_get_page (PAL_ASSERT | PAL_ZERO);
pd[pde_idx] = pde_create (pt);
}
pt[pte_idx] = pte_create_kernel (vaddr, !in_kernel_text);
}
/* Store the physical address of the page directory into CR3
aka PDBR (page directory base register). This activates our
new page tables immediately. See [IA32-v2a] "MOV--Move
to/from Control Registers" and [IA32-v3a] 3.7.5 Base Address
of the Page Directory. */
asm volatile ("movl %0, %%cr3" : : "r" (vtop (base_page_dir)));
}
/* Breaks the kernel command line into words and returns them as
an argv-like array. */
static char **
read_command_line (void)
{
static char *argv[LOADER_ARGS_LEN / 2 + 1];
char *p, *end;
int argc;
int i;
argc = *(uint32_t *) ptov (LOADER_ARG_CNT);
p = ptov (LOADER_ARGS);
end = p + LOADER_ARGS_LEN;
for (i = 0; i < argc; i++)
{
if (p >= end)
PANIC ("command line arguments overflow");
argv[i] = p;
p += strnlen (p, end - p) + 1;
}
argv[argc] = NULL;
/* Print kernel command line. */
printf ("Kernel command line:");
for (i = 0; i < argc; i++)
if (strchr (argv[i], ' ') == NULL)
printf (" %s", argv[i]);
else
printf (" '%s'", argv[i]);
printf ("\n");
return argv;
}
/* Parses options in ARGV[ ]
and returns the first non-option argument. */
static char **
parse_options (char **argv)
{
for (; *argv != NULL && **argv == '-'; argv++)
{
char *save_ptr;
char *name = strtok_r (*argv, "=", &save_ptr);
char *value = strtok_r (NULL, "", &save_ptr);
if (!strcmp (name, "-h"))
usage ();
else if (!strcmp (name, "-q"))
power_off_when_done = true;
else if (!strcmp (name, "-r"))
reboot_when_done = true;
#ifdef FILESYS
else if (!strcmp (name, "-f"))
format_filesys = true;
#endif
else if (!strcmp (name, "-rs"))
random_init (atoi (value));
else if (!strcmp (name, "-mlfqs"))
thread_mlfqs = true;
#ifdef USERPROG
else if (!strcmp (name, "-ul"))
user_page_limit = atoi (value);
#endif
else
PANIC ("unknown option `%s' (use -h for help)", name);
}
/* Initialize the random number generator based on the system
time. This has no effect if an "-rs" option was specified.
When running under Bochs, this is not enough by itself to
get a good seed value, because the pintos script sets the
initial time to a predictable value, not to the local time,
for reproducibility. To fix this, give the "-r" option to
the pintos script to request real time execution. */
random_init (rtc_get_time ());
return argv;
}
/* Runs the task specified in ARGV[1]. */
static void
run_task (char **argv)
{
const char *task = argv[1];
printf ("Executing '%s':\n", task);
#ifdef USERPROG
process_wait (process_execute (task));
#else
run_test (task);
#endif
printf ("Execution of '%s' complete.\n", task);
}
/* Executes all of the actions specified in ARGV[]
up to the null pointer sentinel. */
static void
run_actions (char **argv)
{
/* An action. */
struct action
{
char *name; /* Action name. */
int argc; /* # of args, including action name. */
void (*function) (char **argv); /* Function to execute action. */
};
/* Table of supported actions. */
static const struct action actions[] =
{
{"run", 2, run_task},
#ifdef FILESYS
{"ls", 1, fsutil_ls},
{"cat", 2, fsutil_cat},
{"rm", 2, fsutil_rm},
{"extract", 1, fsutil_extract},
{"append", 2, fsutil_append},
#endif
{NULL, 0, NULL},
};
while (*argv != NULL)
{
const struct action *a;
int i;
/* Find action name. */
for (a = actions; ; a++)
if (a->name == NULL)
PANIC ("unknown action `%s' (use -h for help)", *argv);
else if (!strcmp (*argv, a->name))
break;
/* Check for required arguments. */
for (i = 1; i < a->argc; i++)
if (argv[i] == NULL)
PANIC ("action `%s' requires %d argument(s)", *argv, a->argc - 1);
/* Invokes action and advance. */
a->function (argv);
argv += a->argc;
}
}
/* Prints a kernel command line help message and powers off the
machine. */
static void
usage (void)
{
printf ("\nCommand line syntax: [OPTION...] [ACTION...]\n"
"Options must precede actions.\n"
"Actions are executed in the order specified.\n"
"\nAvailable actions:\n"
#ifdef USERPROG
" run 'PROG [ARG...]' Run PROG and wait for it to complete.\n"
#else
" run TEST Run TEST.\n"
#endif
#ifdef FILESYS
" ls List files in the root directory.\n"
" cat FILE Print FILE to the console.\n"
" rm FILE Delete FILE.\n"
"Use these actions indirectly via `pintos' -g and -p options:\n"
" extract Untar from scratch disk into file system.\n"
" append FILE Append FILE to tar file on scratch disk.\n"
#endif
"\nOptions:\n"
" -h Print this help message and power off.\n"
" -q Power off VM after actions or on panic.\n"
" -r Reboot after actions.\n"
" -f Format file system disk during startup.\n"
" -rs=SEED Set random number seed to SEED.\n"
" -mlfqs Use multi-level feedback queue scheduler.\n"
#ifdef USERPROG
" -ul=COUNT Limit user memory to COUNT pages.\n"
#endif
);
power_off ();
}
/* Keyboard control register port. */
#define CONTROL_REG 0x64
/* Reboots the machine via the keyboard controller. */
void
reboot (void)
{
int i;
printf ("Rebooting...\n");
/* See [kbd] for details on how to program the keyboard
* controller. */
for (i = 0; i < 100; i++)
{
int j;
/* Poll keyboard controller's status byte until
* 'input buffer empty' is reported. */
for (j = 0; j < 0x10000; j++)
{
if ((inb (CONTROL_REG) & 0x02) == 0)
break;
timer_udelay (2);
}
timer_udelay (50);
/* Pulse bit 0 of the output port P2 of the keyboard controller.
* This will reset the CPU. */
outb (CONTROL_REG, 0xfe);
timer_udelay (50);
}
}
/* Powers down the machine we're running on,
as long as we're running on Bochs or QEMU. */
void
power_off (void)
{
const char s[] = "Shutdown";
const char *p;
#ifdef FILESYS
filesys_done ();
#endif
print_stats ();
printf ("Powering off...\n");
serial_flush ();
for (p = s; *p != '\0'; p++)
outb (0x8900, *p);
asm volatile ("cli; hlt" : : : "memory");
printf ("still running...\n");
for (;;);
}
/* Print statistics about PintOS execution. */
static void
print_stats (void)
{
timer_print_stats ();
thread_print_stats ();
#ifdef FILESYS
disk_print_stats ();
#endif
console_print_stats ();
kbd_print_stats ();
#ifdef USERPROG
exception_print_stats ();
#endif
}
| 10cm | trunk/10cm/pintos/src/threads/init.c | C | oos | 11,667 |
#include "threads/palloc.h"
#include <bitmap.h>
#include <debug.h>
#include <inttypes.h>
#include <round.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "threads/init.h"
#include "threads/loader.h"
#include "threads/synch.h"
#include "threads/vaddr.h"
/* Page allocator. Hands out memory in page-size (or
page-multiple) chunks. See malloc.h for an allocator that
hands out smaller chunks.
System memory is divided into two "pools" called the kernel
and user pools. The user pool is for user (virtual) memory
pages, the kernel pool for everything else. The idea here is
that the kernel needs to have memory for its own operations
even if user processes are swapping like mad.
By default, half of system RAM is given to the kernel pool and
half to the user pool. That should be huge overkill for the
kernel pool, but that is just fine for demonstration purposes. */
/* A memory pool. */
struct pool
{
struct lock lock; /* Mutual exclusion. */
struct bitmap *used_map; /* Bitmap of free pages. */
uint8_t *base; /* Base of pool. */
};
/* Two pools: one for kernel data, one for user pages. */
struct pool kernel_pool, user_pool;
/* Maximum number of pages to put in user pool. */
size_t user_page_limit = SIZE_MAX;
static void init_pool (struct pool *, void *base, size_t page_cnt,
const char *name);
static bool page_from_pool (const struct pool *, void *page);
/* Initializes the page allocator. */
void
palloc_init (void)
{
/* End of the kernel as recorded by the linker.
See kernel.lds.S. */
extern char _end;
/* Free memory. */
uint8_t *free_start = pg_round_up (&_end);
uint8_t *free_end = ptov (ram_pages * PGSIZE);
size_t free_pages = (free_end - free_start) / PGSIZE;
size_t user_pages = free_pages / 2;
size_t kernel_pages;
if (user_pages > user_page_limit)
user_pages = user_page_limit;
kernel_pages = free_pages - user_pages;
/* Give half of memory to kernel, half to user. */
init_pool (&kernel_pool, free_start, kernel_pages, "kernel pool");
init_pool (&user_pool, free_start + kernel_pages * PGSIZE,
user_pages, "user pool");
}
/* Obtains and returns a group of PAGE_CNT contiguous free pages.
If PAL_USER is set, the pages are obtained from the user pool,
otherwise from the kernel pool. If PAL_ZERO is set in FLAGS,
the pages are filled with zeros. If too few pages are
available, returns a null pointer, unless PAL_ASSERT is set in
FLAGS, in which case the kernel panics. */
void *
palloc_get_multiple (enum palloc_flags flags, size_t page_cnt)
{
struct pool *pool = flags & PAL_USER ? &user_pool : &kernel_pool;
void *pages;
size_t page_idx;
if (page_cnt == 0)
return NULL;
lock_acquire (&pool->lock);
page_idx = bitmap_scan_and_flip (pool->used_map, 0, page_cnt, false);
lock_release (&pool->lock);
if (page_idx != BITMAP_ERROR)
pages = pool->base + PGSIZE * page_idx;
else
pages = NULL;
if (pages != NULL)
{
if (flags & PAL_ZERO)
memset (pages, 0, PGSIZE * page_cnt);
}
else
{
if (flags & PAL_ASSERT)
PANIC ("palloc_get: out of pages");
}
return pages;
}
/* Obtains a single free page and returns its kernel virtual
address.
If PAL_USER is set, the page is obtained from the user pool,
otherwise from the kernel pool. If PAL_ZERO is set in FLAGS,
then the page is filled with zeros. If no pages are
available, returns a null pointer, unless PAL_ASSERT is set in
FLAGS, in which case the kernel panics. */
void *
palloc_get_page (enum palloc_flags flags)
{
return palloc_get_multiple (flags, 1);
}
/* Frees the PAGE_CNT pages starting at PAGES. */
void
palloc_free_multiple (void *pages, size_t page_cnt)
{
struct pool *pool;
size_t page_idx;
ASSERT (pg_ofs (pages) == 0);
if (pages == NULL || page_cnt == 0)
return;
if (page_from_pool (&kernel_pool, pages))
pool = &kernel_pool;
else if (page_from_pool (&user_pool, pages))
pool = &user_pool;
else
NOT_REACHED ();
page_idx = pg_no (pages) - pg_no (pool->base);
#ifndef NDEBUG
memset (pages, 0xcc, PGSIZE * page_cnt);
#endif
ASSERT (bitmap_all (pool->used_map, page_idx, page_cnt));
bitmap_set_multiple (pool->used_map, page_idx, page_cnt, false);
}
/* Frees the page at PAGE. */
void
palloc_free_page (void *page)
{
palloc_free_multiple (page, 1);
}
/* Initializes pool P as starting at START and ending at END,
naming it NAME for debugging purposes. */
static void
init_pool (struct pool *p, void *base, size_t page_cnt, const char *name)
{
/* We will put the pool's used_map at its base.
Calculate the space needed for the bitmap
and subtract it from the pool's size. */
size_t bm_pages = DIV_ROUND_UP (bitmap_buf_size (page_cnt), PGSIZE);
if (bm_pages > page_cnt)
PANIC ("Not enough memory in %s for bitmap.", name);
page_cnt -= bm_pages;
printf ("%zu pages available in %s.\n", page_cnt, name);
/* Initialize the pool. */
lock_init (&p->lock);
p->used_map = bitmap_create_in_buf (page_cnt, base, bm_pages * PGSIZE);
p->base = base + bm_pages * PGSIZE;
}
/* Returns true if PAGE was allocated from POOL,
false otherwise. */
static bool
page_from_pool (const struct pool *pool, void *page)
{
size_t page_no = pg_no (page);
size_t start_page = pg_no (pool->base);
size_t end_page = start_page + bitmap_size (pool->used_map);
return page_no >= start_page && page_no < end_page;
}
| 10cm | trunk/10cm/pintos/src/threads/palloc.c | C | oos | 5,605 |
#include "threads/malloc.h"
#include <debug.h>
#include <list.h>
#include <round.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "threads/palloc.h"
#include "threads/synch.h"
#include "threads/vaddr.h"
/* A simple implementation of malloc().
The size of each request, in bytes, is rounded up to a power
of 2 and assigned to the "descriptor" that manages blocks of
that size. The descriptor keeps a list of free blocks. If
the free list is nonempty, one of its blocks is used to
satisfy the request.
Otherwise, a new page of memory, called an "arena", is
obtained from the page allocator (if none is available,
malloc() returns a null pointer). The new arena is divided
into blocks, all of which are added to the descriptor's free
list. Then we return one of the new blocks.
When we free a block, we add it to its descriptor's free list.
But if the arena that the block was in now has no in-use
blocks, we remove all of the arena's blocks from the free list
and give the arena back to the page allocator.
We cannot handle blocks bigger than 2 kB using this scheme,
because they're too big to fit in a single page with a
descriptor. We handle those by allocating contiguous pages
with the page allocator and sticking the allocation size at
the beginning of the allocated block's arena header. */
/* Descriptor. */
struct desc
{
size_t block_size; /* Size of each element in bytes. */
size_t blocks_per_arena; /* Number of blocks in an arena. */
struct list free_list; /* List of free blocks. */
struct lock lock; /* Lock. */
};
/* Magic number for detecting arena corruption. */
#define ARENA_MAGIC 0x9a548eed
/* Arena. */
struct arena
{
unsigned magic; /* Always set to ARENA_MAGIC. */
struct desc *desc; /* Owning descriptor, null for big block. */
size_t free_cnt; /* Free blocks; pages in big block. */
};
/* Free block. */
struct block
{
struct list_elem free_elem; /* Free list element. */
};
/* Our set of descriptors. */
static struct desc descs[10]; /* Descriptors. */
static size_t desc_cnt; /* Number of descriptors. */
static struct arena *block_to_arena (struct block *);
static struct block *arena_to_block (struct arena *, size_t idx);
/* Initializes the malloc() descriptors. */
void
malloc_init (void)
{
size_t block_size;
for (block_size = 16; block_size < PGSIZE / 2; block_size *= 2)
{
struct desc *d = &descs[desc_cnt++];
ASSERT (desc_cnt <= sizeof descs / sizeof *descs);
d->block_size = block_size;
d->blocks_per_arena = (PGSIZE - sizeof (struct arena)) / block_size;
list_init (&d->free_list);
lock_init (&d->lock);
}
}
/* Obtains and returns a new block of at least SIZE bytes.
Returns a null pointer if memory is not available. */
void *
malloc (size_t size)
{
struct desc *d;
struct block *b;
struct arena *a;
/* A null pointer satisfies a request for 0 bytes. */
if (size == 0)
return NULL;
/* Find the smallest descriptor that satisfies a SIZE byte
request. */
for (d = descs; d < descs + desc_cnt; d++)
if (d->block_size >= size)
break;
if (d == descs + desc_cnt)
{
/* SIZE is too big for any descriptor.
Allocate enough pages to hold SIZE plus an arena. */
size_t page_cnt = DIV_ROUND_UP (size + sizeof *a, PGSIZE);
a = palloc_get_multiple (0, page_cnt);
if (a == NULL)
return NULL;
/* Initialize the arena to indicate a big block of PAGE_CNT
pages, and return it. */
a->magic = ARENA_MAGIC;
a->desc = NULL;
a->free_cnt = page_cnt;
return a + 1;
}
lock_acquire (&d->lock);
/* If the free list is empty, create a new arena. */
if (list_empty (&d->free_list))
{
size_t i;
/* Allocate a page. */
a = palloc_get_page (0);
if (a == NULL)
{
lock_release (&d->lock);
return NULL;
}
/* Initialize arena and add its blocks to the free list. */
a->magic = ARENA_MAGIC;
a->desc = d;
a->free_cnt = d->blocks_per_arena;
for (i = 0; i < d->blocks_per_arena; i++)
{
struct block *b = arena_to_block (a, i);
list_push_back (&d->free_list, &b->free_elem);
}
}
/* Get a block from free list and return it. */
b = list_entry (list_pop_front (&d->free_list), struct block, free_elem);
a = block_to_arena (b);
a->free_cnt--;
lock_release (&d->lock);
return b;
}
/* Allocates and return A times B bytes initialized to zeroes.
Returns a null pointer if memory is not available. */
void *
calloc (size_t a, size_t b)
{
void *p;
size_t size;
/* Calculate block size and make sure that it fits in size_t. */
size = a * b;
if (size < a || size < b)
return NULL;
/* Allocate and zero memory. */
p = malloc (size);
if (p != NULL)
memset (p, 0, size);
return p;
}
/* Returns the number of bytes allocated for BLOCK. */
static size_t
block_size (void *block)
{
struct block *b = block;
struct arena *a = block_to_arena (b);
struct desc *d = a->desc;
return d != NULL ? d->block_size : PGSIZE * a->free_cnt - pg_ofs (block);
}
/* Attempts to resize OLD_BLOCK to NEW_SIZE bytes, possibly
moving it in the process.
If successful, returns the new block; on failure, returns a
null pointer.
A call with null OLD_BLOCK is equivalent to malloc(NEW_SIZE).
A call with 0 NEW_SIZE is equivalent to free(OLD_BLOCK). */
void *
realloc (void *old_block, size_t new_size)
{
if (new_size == 0)
{
free (old_block);
return NULL;
}
else
{
void *new_block = malloc (new_size);
if (old_block != NULL && new_block != NULL)
{
size_t old_size = block_size (old_block);
size_t min_size = new_size < old_size ? new_size : old_size;
memcpy (new_block, old_block, min_size);
free (old_block);
}
return new_block;
}
}
/* Frees block P, which must have been previously allocated with
malloc(), calloc(), or realloc(). */
void
free (void *p)
{
if (p != NULL)
{
struct block *b = p;
struct arena *a = block_to_arena (b);
struct desc *d = a->desc;
if (d != NULL)
{
/* It's a normal block. We handle it here. */
#ifndef NDEBUG
/* Clear the block to help detect use-after-free bugs. */
memset (b, 0xcc, d->block_size);
#endif
lock_acquire (&d->lock);
/* Add block to free list. */
list_push_front (&d->free_list, &b->free_elem);
/* If the arena is now entirely unused, free it.. */
if (++a->free_cnt >= d->blocks_per_arena)
{
size_t i;
ASSERT (a->free_cnt == d->blocks_per_arena);
for (i = 0; i < d->blocks_per_arena; i++)
{
struct block *b = arena_to_block (a, i);
list_remove (&b->free_elem);
}
palloc_free_page (a);
}
lock_release (&d->lock);
}
else
{
/* It's a big block. Free its pages. */
palloc_free_multiple (a, a->free_cnt);
return;
}
}
}
/* Returns the arena that block B is inside. */
static struct arena *
block_to_arena (struct block *b)
{
struct arena *a = pg_round_down (b);
/* Check the arena is valid. */
ASSERT (a != NULL);
ASSERT (a->magic == ARENA_MAGIC);
/* Check that the block is properly aligned for the arena. */
ASSERT (a->desc == NULL
|| (pg_ofs (b) - sizeof *a) % a->desc->block_size == 0);
ASSERT (a->desc != NULL || pg_ofs (b) == sizeof *a);
return a;
}
/* Returns the (IDX - 1)'th block within arena A. */
static struct block *
arena_to_block (struct arena *a, size_t idx)
{
ASSERT (a != NULL);
ASSERT (a->magic == ARENA_MAGIC);
ASSERT (idx < a->desc->blocks_per_arena);
return (struct block *) ((uint8_t *) a
+ sizeof *a
+ idx * a->desc->block_size);
}
| 10cm | trunk/10cm/pintos/src/threads/malloc.c | C | oos | 8,233 |
#ifndef THREADS_VADDR_H
#define THREADS_VADDR_H
#include <debug.h>
#include <stdint.h>
#include <stdbool.h>
#include "threads/loader.h"
/* Functions and macros for working with virtual addresses.
See pte.h for functions and macros specifically for x86
hardware page tables. */
#define BITMASK(SHIFT, CNT) (((1ul << (CNT)) - 1) << (SHIFT))
/* Page offset (bits 0:12). */
#define PGSHIFT 0 /* Index of first offset bit. */
#define PGBITS 12 /* Number of offset bits. */
#define PGSIZE (1 << PGBITS) /* Bytes in a page. */
#define PGMASK BITMASK(PGSHIFT, PGBITS) /* Page offset bits (0:12). */
/* Offset within a page. */
static inline unsigned pg_ofs (const void *va) {
return (uintptr_t) va & PGMASK;
}
/* Virtual page number. */
static inline uintptr_t pg_no (const void *va) {
return (uintptr_t) va >> PGBITS;
}
/* Round up to nearest page boundary. */
static inline void *pg_round_up (const void *va) {
return (void *) (((uintptr_t) va + PGSIZE - 1) & ~PGMASK);
}
/* Round down to nearest page boundary. */
static inline void *pg_round_down (const void *va) {
return (void *) ((uintptr_t) va & ~PGMASK);
}
/* Base address of the 1:1 physical-to-virtual mapping. Physical
memory is mapped starting at this virtual address. Thus,
physical address 0 is accessible at PHYS_BASE, physical
address address 0x1234 at (uint8_t *) PHYS_BASE + 0x1234, and
so on.
This address also marks the end of user programs' address
space. Up to this point in memory, user programs are allowed
to map whatever they like. At this point and above, the
virtual address space belongs to the kernel. */
#define PHYS_BASE ((void *) LOADER_PHYS_BASE)
/* Returns true if VADDR is a user virtual address. */
static inline bool
is_user_vaddr (const void *vaddr)
{
return vaddr < PHYS_BASE;
}
/* Returns true if VADDR is a kernel virtual address. */
static inline bool
is_kernel_vaddr (const void *vaddr)
{
return vaddr >= PHYS_BASE;
}
/* Returns kernel virtual address at which physical address PADDR
is mapped. */
static inline void *
ptov (uintptr_t paddr)
{
ASSERT ((void *) paddr < PHYS_BASE);
return (void *) (paddr + PHYS_BASE);
}
/* Returns physical address at which kernel virtual address VADDR
is mapped. */
static inline uintptr_t
vtop (const void *vaddr)
{
ASSERT (is_kernel_vaddr (vaddr));
return (uintptr_t) vaddr - (uintptr_t) PHYS_BASE;
}
#endif /* threads/vaddr.h */
| 10cm | trunk/10cm/pintos/src/threads/vaddr.h | C | oos | 2,502 |
#### The loader needs to have some way to know the kernel's entry
#### point, that is, the address to which it should jump to start the
#### kernel. We handle this by writing the linker script kernel.lds.S
#### so that this module appears at the very beginning of the kernel
#### image, and then using that as the entry point.
.section .start
.globl start
.func start
# Call main.
start: call main
# main() should not return, but if it does, spin.
1: jmp 1b
.endfunc
| 10cm | trunk/10cm/pintos/src/threads/start.S | Unix Assembly | oos | 474 |
/* This file is derived from source code used in MIT's 6.828
course. The original copyright notice is reproduced in full
below. */
/*
* Copyright (C) 1997 Massachusetts Institute of Technology
*
* This software is being provided by the copyright holders under the
* following license. By obtaining, using and/or copying this software,
* you agree that you have read, understood, and will comply with the
* following terms and conditions:
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose and without fee or royalty is
* hereby granted, provided that the full text of this NOTICE appears on
* ALL copies of the software and documentation or portions thereof,
* including modifications, that you make.
*
* THIS SOFTWARE IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO
* REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
* BUT NOT LIMITATION, COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR
* WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR
* THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY
* THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. COPYRIGHT
* HOLDERS WILL BEAR NO LIABILITY FOR ANY USE OF THIS SOFTWARE OR
* DOCUMENTATION.
*
* The name and trademarks of copyright holders may NOT be used in
* advertising or publicity pertaining to the software without specific,
* written prior permission. Title to copyright in this software and any
* associated documentation will at all times remain with copyright
* holders. See the file AUTHORS which should have accompanied this software
* for a list of all copyright holders.
*
* This file may be derived from previously copyrighted software. This
* copyright applies only to those changes made by the copyright
* holders listed in the AUTHORS file. The rest of this file is covered by
* the copyright notices, if any, listed below.
*/
#ifndef THREADS_IO_H
#define THREADS_IO_H
#include <stddef.h>
#include <stdint.h>
/* Reads and returns a byte from PORT. */
static inline uint8_t
inb (uint16_t port)
{
/* See [IA32-v2a] "IN". */
uint8_t data;
asm volatile ("inb %w1,%0" : "=a" (data) : "d" (port));
return data;
}
/* Reads CNT bytes from PORT, one after another, and stores them
into the buffer starting at ADDR. */
static inline void
insb (uint16_t port, void *addr, size_t cnt)
{
/* See [IA32-v2a] "INS". */
asm volatile ("cld; repne; insb"
: "=D" (addr), "=c" (cnt)
: "d" (port), "0" (addr), "1" (cnt)
: "memory", "cc");
}
/* Reads and returns 16 bits from PORT. */
static inline uint16_t
inw (uint16_t port)
{
uint16_t data;
/* See [IA32-v2a] "IN". */
asm volatile ("inw %w1,%0" : "=a" (data) : "d" (port));
return data;
}
/* Reads CNT 16-bit (halfword) units from PORT, one after
another, and stores them into the buffer starting at ADDR. */
static inline void
insw (uint16_t port, void *addr, size_t cnt)
{
/* See [IA32-v2a] "INS". */
asm volatile ("cld; repne; insw"
: "=D" (addr), "=c" (cnt)
: "d" (port), "0" (addr), "1" (cnt)
: "memory", "cc");
}
/* Reads and returns 32 bits from PORT. */
static inline uint32_t
inl (uint16_t port)
{
/* See [IA32-v2a] "IN". */
uint32_t data;
asm volatile ("inl %w1,%0" : "=a" (data) : "d" (port));
return data;
}
/* Reads CNT 32-bit (word) units from PORT, one after another,
and stores them into the buffer starting at ADDR. */
static inline void
insl (uint16_t port, void *addr, size_t cnt)
{
/* See [IA32-v2a] "INS". */
asm volatile ("cld; repne; insl"
: "=D" (addr), "=c" (cnt)
: "d" (port), "0" (addr), "1" (cnt)
: "memory", "cc");
}
/* Writes byte DATA to PORT. */
static inline void
outb (uint16_t port, uint8_t data)
{
/* See [IA32-v2b] "OUT". */
asm volatile ("outb %0,%w1" : : "a" (data), "d" (port));
}
/* Writes to PORT each byte of data in the CNT-byte buffer
starting at ADDR. */
static inline void
outsb (uint16_t port, const void *addr, size_t cnt)
{
/* See [IA32-v2b] "OUTS". */
asm volatile ("cld; repne; outsb"
: "=S" (addr), "=c" (cnt)
: "d" (port), "0" (addr), "1" (cnt)
: "cc");
}
/* Writes the 16-bit DATA to PORT. */
static inline void
outw (uint16_t port, uint16_t data)
{
/* See [IA32-v2b] "OUT". */
asm volatile ("outw %0,%w1" : : "a" (data), "d" (port));
}
/* Writes to PORT each 16-bit unit (halfword) of data in the
CNT-halfword buffer starting at ADDR. */
static inline void
outsw (uint16_t port, const void *addr, size_t cnt)
{
/* See [IA32-v2b] "OUTS". */
asm volatile ("cld; repne; outsw"
: "=S" (addr), "=c" (cnt)
: "d" (port), "0" (addr), "1" (cnt)
: "cc");
}
/* Writes the 32-bit DATA to PORT. */
static inline void
outl (uint16_t port, uint32_t data)
{
/* See [IA32-v2b] "OUT". */
asm volatile ("outl %0,%w1" : : "a" (data), "d" (port));
}
/* Writes to PORT each 32-bit unit (word) of data in the CNT-word
buffer starting at ADDR. */
static inline void
outsl (uint16_t port, const void *addr, size_t cnt)
{
/* See [IA32-v2b] "OUTS". */
asm volatile ("cld; repne; outsl"
: "=S" (addr), "=c" (cnt)
: "d" (port), "0" (addr), "1" (cnt)
: "cc");
}
#endif /* threads/io.h */
| 10cm | trunk/10cm/pintos/src/threads/io.h | C | oos | 5,464 |
# -*- makefile -*-
os.dsk: DEFINES =
KERNEL_SUBDIRS = threads devices lib lib/kernel $(TEST_SUBDIRS)
TEST_SUBDIRS = tests/threads
GRADING_FILE = $(SRCDIR)/tests/threads/Grading
SIMULATOR = --bochs
| 10cm | trunk/10cm/pintos/src/threads/.svn/text-base/Make.vars.svn-base | Makefile | oos | 198 |
#include "threads/interrupt.h"
#include <debug.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include "threads/flags.h"
#include "threads/intr-stubs.h"
#include "threads/io.h"
#include "threads/thread.h"
#include "threads/vaddr.h"
#include "devices/timer.h"
/* Programmable Interrupt Controller (PIC) registers.
A PC has two PICs, called the master and slave PICs, with the
slave attached ("cascaded") to the master IRQ line 2. */
#define PIC0_CTRL 0x20 /* Master PIC control register address. */
#define PIC0_DATA 0x21 /* Master PIC data register address. */
#define PIC1_CTRL 0xa0 /* Slave PIC control register address. */
#define PIC1_DATA 0xa1 /* Slave PIC data register address. */
/* Number of x86 interrupts. */
#define INTR_CNT 256
/* The Interrupt Descriptor Table (IDT). The format is fixed by
the CPU. See [IA32-v3a] sections 5.10 "Interrupt Descriptor
Table (IDT)", 5.11 "IDT Descriptors", 5.12.1.2 "Flag Usage By
Exception- or Interrupt-Handler Procedure". */
static uint64_t idt[INTR_CNT];
/* Interrupt handler functions for each interrupt. */
static intr_handler_func *intr_handlers[INTR_CNT];
/* Names for each interrupt, for debugging purposes. */
static const char *intr_names[INTR_CNT];
/* External interrupts are generated by devices outside the
CPU, such as the timer. External interrupts run with
interrupts turned off, so they never nest, nor are they ever
pre-empted. Handlers for external interrupts also may not
sleep, although they may invoke intr_yield_on_return() to
request that a new process be scheduled just before the
interrupt returns. */
static bool in_external_intr; /* Are we processing an external interrupt? */
static bool yield_on_return; /* Should we yield on interrupt return? */
/* Programmable Interrupt Controller helpers. */
static void pic_init (void);
static void pic_end_of_interrupt (int irq);
/* Interrupt Descriptor Table helpers. */
static uint64_t make_intr_gate (void (*) (void), int dpl);
static uint64_t make_trap_gate (void (*) (void), int dpl);
static inline uint64_t make_idtr_operand (uint16_t limit, void *base);
/* Interrupt handlers. */
void intr_handler (struct intr_frame *args);
/* Returns the current interrupt status. */
enum intr_level
intr_get_level (void)
{
uint32_t flags;
/* Push the flags register on the processor stack, then pop the
value off the stack into `flags'. See [IA32-v2b] "PUSHF"
and "POP" and [IA32-v3a] 5.8.1 "Masking Maskable Hardware
Interrupts". */
asm volatile ("pushfl; popl %0" : "=g" (flags));
return flags & FLAG_IF ? INTR_ON : INTR_OFF;
}
/* Enables or disables interrupts as specified by LEVEL and
returns the previous interrupt status. */
enum intr_level
intr_set_level (enum intr_level level)
{
return level == INTR_ON ? intr_enable () : intr_disable ();
}
/* Enables interrupts and returns the previous interrupt status. */
enum intr_level
intr_enable (void)
{
enum intr_level old_level = intr_get_level ();
ASSERT (!intr_context ());
/* Enable interrupts by setting the interrupt flag.
See [IA32-v2b] "STI" and [IA32-v3a] 5.8.1 "Masking Maskable
Hardware Interrupts". */
asm volatile ("sti");
return old_level;
}
/* Disable interrupts and returns the previous interrupt status. */
enum intr_level
intr_disable (void)
{
enum intr_level old_level = intr_get_level ();
/* Disable interrupts by clearing the interrupt flag.
See [IA32-v2b] "CLI" and [IA32-v3a] 5.8.1 "Masking Maskable
Hardware Interrupts". */
asm volatile ("cli" : : : "memory");
return old_level;
}
/* Initializes the interrupt system. */
void
intr_init (void)
{
uint64_t idtr_operand;
int i;
/* Initialize interrupt controller. */
pic_init ();
/* Initialize IDT. */
for (i = 0; i < INTR_CNT; i++)
idt[i] = make_intr_gate (intr_stubs[i], 0);
/* Load IDT register.
See [IA32-v2a] "LIDT" and [IA32-v3a] 5.10 "Interrupt
Descriptor Table (IDT)". */
idtr_operand = make_idtr_operand (sizeof idt - 1, idt);
asm volatile ("lidt %0" : : "m" (idtr_operand));
/* Initialize intr_names. */
for (i = 0; i < INTR_CNT; i++)
intr_names[i] = "unknown";
intr_names[0] = "#DE Divide Error";
intr_names[1] = "#DB Debug Exception";
intr_names[2] = "NMI Interrupt";
intr_names[3] = "#BP Breakpoint Exception";
intr_names[4] = "#OF Overflow Exception";
intr_names[5] = "#BR BOUND Range Exceeded Exception";
intr_names[6] = "#UD Invalid Opcode Exception";
intr_names[7] = "#NM Device Not Available Exception";
intr_names[8] = "#DF Double Fault Exception";
intr_names[9] = "Coprocessor Segment Overrun";
intr_names[10] = "#TS Invalid TSS Exception";
intr_names[11] = "#NP Segment Not Present";
intr_names[12] = "#SS Stack Fault Exception";
intr_names[13] = "#GP General Protection Exception";
intr_names[14] = "#PF Page-Fault Exception";
intr_names[16] = "#MF x87 FPU Floating-Point Error";
intr_names[17] = "#AC Alignment Check Exception";
intr_names[18] = "#MC Machine-Check Exception";
intr_names[19] = "#XF SIMD Floating-Point Exception";
}
/* Registers interrupt VEC_NO to invoke HANDLER with descriptor
privilege level DPL. Names the interrupt NAME for debugging
purposes. The interrupt handler will be invoked with
interrupt status set to LEVEL. */
static void
register_handler (uint8_t vec_no, int dpl, enum intr_level level,
intr_handler_func *handler, const char *name)
{
ASSERT (intr_handlers[vec_no] == NULL);
if (level == INTR_ON)
idt[vec_no] = make_trap_gate (intr_stubs[vec_no], dpl);
else
idt[vec_no] = make_intr_gate (intr_stubs[vec_no], dpl);
intr_handlers[vec_no] = handler;
intr_names[vec_no] = name;
}
/* Registers external interrupt VEC_NO to invoke HANDLER, which
is named NAME for debugging purposes. The handler will
execute with interrupts disabled. */
void
intr_register_ext (uint8_t vec_no, intr_handler_func *handler,
const char *name)
{
ASSERT (vec_no >= 0x20 && vec_no <= 0x2f);
register_handler (vec_no, 0, INTR_OFF, handler, name);
}
/* Registers internal interrupt VEC_NO to invoke HANDLER, which
is named NAME for debugging purposes. The interrupt handler
will be invoked with interrupt status LEVEL.
The handler will have descriptor privilege level DPL, meaning
that it can be invoked intentionally when the processor is in
the DPL or lower-numbered ring. In practice, DPL==3 allows
user mode to invoke the interrupts and DPL==0 prevents such
invocation. Faults and exceptions that occur in user mode
still cause interrupts with DPL==0 to be invoked. See
[IA32-v3a] sections 4.5 - "Privilege Levels" and 4.8.1.1
"Accessing Nonconforming Code Segments" for further
discussion. */
void
intr_register_int (uint8_t vec_no, int dpl, enum intr_level level,
intr_handler_func *handler, const char *name)
{
ASSERT (vec_no < 0x20 || vec_no > 0x2f);
register_handler (vec_no, dpl, level, handler, name);
}
/* Returns true during processing of an external interrupt
and false at all other times. */
bool
intr_context (void)
{
return in_external_intr;
}
/* During processing of an external interrupt, directs the
interrupt handler to yield to a new process just before
returning from the interrupt. May not be called at any other
time. */
void
intr_yield_on_return (void)
{
ASSERT (intr_context ());
yield_on_return = true;
}
/* 8259A Programmable Interrupt Controller. */
/* Initializes the PICs. Refer to [8259A] for details.
By default, interrupts 0...15 delivered by the PICs will go to
interrupt vectors 0...15. Those vectors are also used for CPU
traps and exceptions, so we reprogram the PICs so that
interrupts 0...15 are delivered to interrupt vectors 32...47
(0x20...0x2f) instead. */
static void
pic_init (void)
{
/* Mask all interrupts on both PICs. */
outb (PIC0_DATA, 0xff);
outb (PIC1_DATA, 0xff);
/* Initialize master. */
outb (PIC0_CTRL, 0x11); /* ICW1: single mode, edge triggered, expect ICW4. */
outb (PIC0_DATA, 0x20); /* ICW2: line IR0...7 -> irq 0x20...0x27. */
outb (PIC0_DATA, 0x04); /* ICW3: slave PIC on line IR2. */
outb (PIC0_DATA, 0x01); /* ICW4: 8086 mode, normal EOI, non-buffered. */
/* Initialize slave. */
outb (PIC1_CTRL, 0x11); /* ICW1: single mode, edge triggered, expect ICW4. */
outb (PIC1_DATA, 0x28); /* ICW2: line IR0...7 -> irq 0x28...0x2f. */
outb (PIC1_DATA, 0x02); /* ICW3: slave ID is 2. */
outb (PIC1_DATA, 0x01); /* ICW4: 8086 mode, normal EOI, non-buffered. */
/* Unmask all interrupts. */
outb (PIC0_DATA, 0x00);
outb (PIC1_DATA, 0x00);
}
/* Sends an end-of-interrupt signal to the PIC for the given IRQ.
If we don't acknowledge the IRQ, it will never be delivered to
us again, so this is important. */
static void
pic_end_of_interrupt (int irq)
{
ASSERT (irq >= 0x20 && irq < 0x30);
/* Acknowledge master PIC. */
outb (0x20, 0x20);
/* Acknowledge slave PIC if this is a slave interrupt. */
if (irq >= 0x28)
outb (0xa0, 0x20);
}
/* Creates an gate that invokes FUNCTION.
The gate has descriptor privilege level DPL, meaning that it
can be invoked intentionally when the processor is in the DPL
or lower-numbered ring. In practice, DPL==3 allows user mode
to call into the gate and DPL==0 prevents such calls. Faults
and exceptions that occur in user mode still cause gates with
DPL==0 to be invoked. See: [IA32-v3a] sections 4.5 "Privilege
Levels" and 4.8.1.1 "Accessing Nonconforming Code Segments"
for further discussion.
TYPE must be either 14 (for an interrupt gate) or 15 (for a
trap gate). The difference is that entering an interrupt gate
disables interrupts, but entering a trap gate does not. See
[IA32-v3a] section 5.12.1.2 "Flag Usage By Exception- or
Interrupt-Handler Procedure" for discussion. */
static uint64_t
make_gate (void (*function) (void), int dpl, int type)
{
uint32_t e0, e1;
ASSERT (function != NULL);
ASSERT (dpl >= 0 && dpl <= 3);
ASSERT (type >= 0 && type <= 15);
e0 = (((uint32_t) function & 0xffff) /* Offset 15:0. */
| (SEL_KCSEG << 16)); /* Target code segment. */
e1 = (((uint32_t) function & 0xffff0000) /* Offset 31:16. */
| (1 << 15) /* Present. */
| ((uint32_t) dpl << 13) /* Descriptor privilege level. */
| (0 << 12) /* System. */
| ((uint32_t) type << 8)); /* Gate type. */
return e0 | ((uint64_t) e1 << 32);
}
/* Creates an interrupt gate that invokes FUNCTION with the given
DPL. */
static uint64_t
make_intr_gate (void (*function) (void), int dpl)
{
return make_gate (function, dpl, 14);
}
/* Creates a trap gate that invokes FUNCTION with the given
DPL. */
static uint64_t
make_trap_gate (void (*function) (void), int dpl)
{
return make_gate (function, dpl, 15);
}
/* Returns a descriptor that yields the given LIMIT and BASE when
used as an operand for the LIDT instruction. */
static inline uint64_t
make_idtr_operand (uint16_t limit, void *base)
{
return limit | ((uint64_t) (uint32_t) base << 16);
}
/* Interrupt handlers. */
/* Handler for all interrupts, faults and exceptions. This
function is called by the assembly language interrupt stubs in
intr-stubs.S. FRAME describes the interrupt and the
interrupted thread's registers. */
void
intr_handler (struct intr_frame *frame)
{
bool external;
intr_handler_func *handler;
/* External interrupts are special.
We only handle one at a time (so interrupts must be off)
and they need to be acknowledged on the PIC (see below).
An external interrupt handler cannot sleep. */
external = frame->vec_no >= 0x20 && frame->vec_no < 0x30;
if (external)
{
ASSERT (intr_get_level () == INTR_OFF);
ASSERT (!intr_context ());
in_external_intr = true;
yield_on_return = false;
}
/* Invoke the interrupt's handler. */
handler = intr_handlers[frame->vec_no];
if (handler != NULL)
handler (frame);
else if (frame->vec_no == 0x27 || frame->vec_no == 0x2f)
{
/* There is no handler but this interrupt can trigger
spuriously due to a hardware fault or hardware race
condition. Ignore it. */
}
else
{
/* No handler and not spurious. Invoke the unexpected
interrupt handler. */
intr_dump_frame (frame);
PANIC ("Unexpected interrupt");
}
/* Complete the processing of an external interrupt. */
if (external)
{
ASSERT (intr_get_level () == INTR_OFF);
ASSERT (intr_context ());
in_external_intr = false;
pic_end_of_interrupt (frame->vec_no);
if (yield_on_return)
thread_yield ();
}
}
/* Dumps interrupt frame F to the console, for debugging. */
void
intr_dump_frame (const struct intr_frame *f)
{
uint32_t cr2;
/* Store current value of CR2 into `cr2'.
CR2 is the linear address of the last page fault.
See [IA32-v2a] "MOV--Move to/from Control Registers" and
[IA32-v3a] 5.14 "Interrupt 14--Page Fault Exception
(#PF)". */
asm ("movl %%cr2, %0" : "=r" (cr2));
printf ("Interrupt %#04x (%s) at eip=%p\n",
f->vec_no, intr_names[f->vec_no], f->eip);
printf (" cr2=%08"PRIx32" error=%08"PRIx32"\n", cr2, f->error_code);
printf (" eax=%08"PRIx32" ebx=%08"PRIx32" ecx=%08"PRIx32" edx=%08"PRIx32"\n",
f->eax, f->ebx, f->ecx, f->edx);
printf (" esi=%08"PRIx32" edi=%08"PRIx32" esp=%08"PRIx32" ebp=%08"PRIx32"\n",
f->esi, f->edi, (uint32_t) f->esp, f->ebp);
printf (" cs=%04"PRIx16" ds=%04"PRIx16" es=%04"PRIx16" ss=%04"PRIx16"\n",
f->cs, f->ds, f->es, f->ss);
}
/* Returns the name of interrupt VEC. */
const char *
intr_name (uint8_t vec)
{
return intr_names[vec];
}
| 10cm | trunk/10cm/pintos/src/threads/interrupt.c | C | oos | 13,954 |
#include "threads/loader.h"
.text
/* Main interrupt entry point.
An internal or external interrupt starts in one of the
intrNN_stub routines, which push the `struct intr_frame'
frame_pointer, error_code, and vec_no members on the stack,
then jump here.
We save the rest of the `struct intr_frame' members to the
stack, set up some registers as needed by the kernel, and then
call intr_handler(), which actually handles the interrupt.
We "fall through" to intr_exit to return from the interrupt.
*/
.func intr_entry
intr_entry:
/* Save caller's registers. */
pushl %ds
pushl %es
pushl %fs
pushl %gs
pushal
/* Set up kernel environment. */
cld /* String instructions go upward. */
mov $SEL_KDSEG, %eax /* Initialize segment registers. */
mov %eax, %ds
mov %eax, %es
leal 56(%esp), %ebp /* Set up frame pointer. */
/* Call interrupt handler. */
pushl %esp
.globl intr_handler
call intr_handler
addl $4, %esp
.endfunc
/* Interrupt exit.
Restores the caller's registers, discards extra data on the
stack, and returns to the caller.
This is a separate function because it is called directly when
we launch a new user process (see start_process() in
userprog/process.c). */
.globl intr_exit
.func intr_exit
intr_exit:
/* Restore caller's registers. */
popal
popl %gs
popl %fs
popl %es
popl %ds
/* Discard `struct intr_frame' vec_no, error_code,
frame_pointer members. */
addl $12, %esp
/* Return to caller. */
iret
.endfunc
/* Interrupt stubs.
This defines 256 fragments of code, named `intr00_stub'
through `intrff_stub', each of which is used as the entry
point for the corresponding interrupt vector. It also puts
the address of each of these functions in the correct spot in
`intr_stubs', an array of function pointers.
Most of the stubs do this:
1. Push %ebp on the stack (frame_pointer in `struct intr_frame').
2. Push 0 on the stack (error_code).
3. Push the interrupt number on the stack (vec_no).
The CPU pushes an extra "error code" on the stack for a few
interrupts. Because we want %ebp to be where the error code
is, we follow a different path:
1. Push a duplicate copy of the error code on the stack.
2. Replace the original copy of the error code by %ebp.
3. Push the interrupt number on the stack. */
.data
.globl intr_stubs
intr_stubs:
/* This implements steps 1 and 2, described above, in the common
case where we just push a 0 error code. */
#define zero \
pushl %ebp; \
pushl $0
/* This implements steps 1 and 2, described above, in the case
where the CPU already pushed an error code. */
#define REAL \
pushl (%esp); \
movl %ebp, 4(%esp)
/* Emits a stub for interrupt vector NUMBER.
TYPE is `zero', for the case where we push a 0 error code,
or `REAL', if the CPU pushes an error code for us. */
#define STUB(NUMBER, TYPE) \
.text; \
.globl intr##NUMBER##_stub; \
.func intr##NUMBER##_stub; \
intr##NUMBER##_stub: \
TYPE; \
push $0x##NUMBER; \
jmp intr_entry; \
.endfunc; \
\
.data; \
.long intr##NUMBER##_stub;
/* All the stubs. */
STUB(00, zero) STUB(01, zero) STUB(02, zero) STUB(03, zero)
STUB(04, zero) STUB(05, zero) STUB(06, zero) STUB(07, zero)
STUB(08, REAL) STUB(09, zero) STUB(0a, REAL) STUB(0b, REAL)
STUB(0c, zero) STUB(0d, REAL) STUB(0e, REAL) STUB(0f, zero)
STUB(10, zero) STUB(11, REAL) STUB(12, zero) STUB(13, zero)
STUB(14, zero) STUB(15, zero) STUB(16, zero) STUB(17, zero)
STUB(18, REAL) STUB(19, zero) STUB(1a, REAL) STUB(1b, REAL)
STUB(1c, zero) STUB(1d, REAL) STUB(1e, REAL) STUB(1f, zero)
STUB(20, zero) STUB(21, zero) STUB(22, zero) STUB(23, zero)
STUB(24, zero) STUB(25, zero) STUB(26, zero) STUB(27, zero)
STUB(28, zero) STUB(29, zero) STUB(2a, zero) STUB(2b, zero)
STUB(2c, zero) STUB(2d, zero) STUB(2e, zero) STUB(2f, zero)
STUB(30, zero) STUB(31, zero) STUB(32, zero) STUB(33, zero)
STUB(34, zero) STUB(35, zero) STUB(36, zero) STUB(37, zero)
STUB(38, zero) STUB(39, zero) STUB(3a, zero) STUB(3b, zero)
STUB(3c, zero) STUB(3d, zero) STUB(3e, zero) STUB(3f, zero)
STUB(40, zero) STUB(41, zero) STUB(42, zero) STUB(43, zero)
STUB(44, zero) STUB(45, zero) STUB(46, zero) STUB(47, zero)
STUB(48, zero) STUB(49, zero) STUB(4a, zero) STUB(4b, zero)
STUB(4c, zero) STUB(4d, zero) STUB(4e, zero) STUB(4f, zero)
STUB(50, zero) STUB(51, zero) STUB(52, zero) STUB(53, zero)
STUB(54, zero) STUB(55, zero) STUB(56, zero) STUB(57, zero)
STUB(58, zero) STUB(59, zero) STUB(5a, zero) STUB(5b, zero)
STUB(5c, zero) STUB(5d, zero) STUB(5e, zero) STUB(5f, zero)
STUB(60, zero) STUB(61, zero) STUB(62, zero) STUB(63, zero)
STUB(64, zero) STUB(65, zero) STUB(66, zero) STUB(67, zero)
STUB(68, zero) STUB(69, zero) STUB(6a, zero) STUB(6b, zero)
STUB(6c, zero) STUB(6d, zero) STUB(6e, zero) STUB(6f, zero)
STUB(70, zero) STUB(71, zero) STUB(72, zero) STUB(73, zero)
STUB(74, zero) STUB(75, zero) STUB(76, zero) STUB(77, zero)
STUB(78, zero) STUB(79, zero) STUB(7a, zero) STUB(7b, zero)
STUB(7c, zero) STUB(7d, zero) STUB(7e, zero) STUB(7f, zero)
STUB(80, zero) STUB(81, zero) STUB(82, zero) STUB(83, zero)
STUB(84, zero) STUB(85, zero) STUB(86, zero) STUB(87, zero)
STUB(88, zero) STUB(89, zero) STUB(8a, zero) STUB(8b, zero)
STUB(8c, zero) STUB(8d, zero) STUB(8e, zero) STUB(8f, zero)
STUB(90, zero) STUB(91, zero) STUB(92, zero) STUB(93, zero)
STUB(94, zero) STUB(95, zero) STUB(96, zero) STUB(97, zero)
STUB(98, zero) STUB(99, zero) STUB(9a, zero) STUB(9b, zero)
STUB(9c, zero) STUB(9d, zero) STUB(9e, zero) STUB(9f, zero)
STUB(a0, zero) STUB(a1, zero) STUB(a2, zero) STUB(a3, zero)
STUB(a4, zero) STUB(a5, zero) STUB(a6, zero) STUB(a7, zero)
STUB(a8, zero) STUB(a9, zero) STUB(aa, zero) STUB(ab, zero)
STUB(ac, zero) STUB(ad, zero) STUB(ae, zero) STUB(af, zero)
STUB(b0, zero) STUB(b1, zero) STUB(b2, zero) STUB(b3, zero)
STUB(b4, zero) STUB(b5, zero) STUB(b6, zero) STUB(b7, zero)
STUB(b8, zero) STUB(b9, zero) STUB(ba, zero) STUB(bb, zero)
STUB(bc, zero) STUB(bd, zero) STUB(be, zero) STUB(bf, zero)
STUB(c0, zero) STUB(c1, zero) STUB(c2, zero) STUB(c3, zero)
STUB(c4, zero) STUB(c5, zero) STUB(c6, zero) STUB(c7, zero)
STUB(c8, zero) STUB(c9, zero) STUB(ca, zero) STUB(cb, zero)
STUB(cc, zero) STUB(cd, zero) STUB(ce, zero) STUB(cf, zero)
STUB(d0, zero) STUB(d1, zero) STUB(d2, zero) STUB(d3, zero)
STUB(d4, zero) STUB(d5, zero) STUB(d6, zero) STUB(d7, zero)
STUB(d8, zero) STUB(d9, zero) STUB(da, zero) STUB(db, zero)
STUB(dc, zero) STUB(dd, zero) STUB(de, zero) STUB(df, zero)
STUB(e0, zero) STUB(e1, zero) STUB(e2, zero) STUB(e3, zero)
STUB(e4, zero) STUB(e5, zero) STUB(e6, zero) STUB(e7, zero)
STUB(e8, zero) STUB(e9, zero) STUB(ea, zero) STUB(eb, zero)
STUB(ec, zero) STUB(ed, zero) STUB(ee, zero) STUB(ef, zero)
STUB(f0, zero) STUB(f1, zero) STUB(f2, zero) STUB(f3, zero)
STUB(f4, zero) STUB(f5, zero) STUB(f6, zero) STUB(f7, zero)
STUB(f8, zero) STUB(f9, zero) STUB(fa, zero) STUB(fb, zero)
STUB(fc, zero) STUB(fd, zero) STUB(fe, zero) STUB(ff, zero)
| 10cm | trunk/10cm/pintos/src/threads/intr-stubs.S | Motorola 68K Assembly | oos | 7,457 |
#ifndef THREADS_INIT_H
#define THREADS_INIT_H
#include <debug.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/* Physical memory size, in 4kB pages. */
extern size_t ram_pages;
/* Page directory with kernel mappings only. */
extern uint32_t *base_page_dir;
/* -q: Power off when kernel tasks complete? */
extern bool power_off_when_done;
void power_off (void) NO_RETURN;
void reboot (void);
#endif /* threads/init.h */
| 10cm | trunk/10cm/pintos/src/threads/init.h | C | oos | 441 |
#ifndef THREADS_INTERRUPT_H
#define THREADS_INTERRUPT_H
#include <stdbool.h>
#include <stdint.h>
/* Interrupts on or off? */
enum intr_level
{
INTR_OFF, /* Interrupts disabled. */
INTR_ON /* Interrupts enabled. */
};
enum intr_level intr_get_level (void);
enum intr_level intr_set_level (enum intr_level);
enum intr_level intr_enable (void);
enum intr_level intr_disable (void);
/* Interrupt stack frame. */
struct intr_frame
{
/* Pushed by intr_entry in intr-stubs.S.
These are the interrupted task's saved registers. */
uint32_t edi; /* Saved EDI. */
uint32_t esi; /* Saved ESI. */
uint32_t ebp; /* Saved EBP. */
uint32_t esp_dummy; /* Not used. */
uint32_t ebx; /* Saved EBX. */
uint32_t edx; /* Saved EDX. */
uint32_t ecx; /* Saved ECX. */
uint32_t eax; /* Saved EAX. */
uint16_t gs, :16; /* Saved GS segment register. */
uint16_t fs, :16; /* Saved FS segment register. */
uint16_t es, :16; /* Saved ES segment register. */
uint16_t ds, :16; /* Saved DS segment register. */
/* Pushed by intrNN_stub in intr-stubs.S. */
uint32_t vec_no; /* Interrupt vector number. */
/* Sometimes pushed by the CPU,
otherwise for consistency pushed as 0 by intrNN_stub.
The CPU puts it just under `eip', but we move it here. */
uint32_t error_code; /* Error code. */
/* Pushed by intrNN_stub in intr-stubs.S.
This frame pointer eases interpretation of backtraces. */
void *frame_pointer; /* Saved EBP(frame pointer). */
/* Pushed by the CPU.
These are the interrupted task's saved registers. */
void (*eip) (void); /* Next instruction to execute. */
uint16_t cs, :16; /* Code segment for eip. */
uint32_t eflags; /* Saved CPU flags. */
void *esp; /* Saved stack pointer. */
uint16_t ss, :16; /* Data segment for esp. */
};
typedef void intr_handler_func (struct intr_frame *);
void intr_init (void);
void intr_register_ext (uint8_t vec, intr_handler_func *, const char *name);
void intr_register_int (uint8_t vec, int dpl, enum intr_level,
intr_handler_func *, const char *name);
bool intr_context (void);
void intr_yield_on_return (void);
void intr_dump_frame (const struct intr_frame *);
const char *intr_name (uint8_t vec);
#endif /* threads/interrupt.h */
| 10cm | trunk/10cm/pintos/src/threads/interrupt.h | C | oos | 2,590 |
#ifndef THREADS_PTE_H
#define THREADS_PTE_H
#include "threads/vaddr.h"
/* Functions and macros for working with x86 hardware page
tables.
See vaddr.h for more generic functions and macros for virtual
addresses.
Virtual addresses are structured as follows:
31 22 21 12 11 0
+----------------------+----------------------+----------------------+
| Page Directory Index | Page Table Index | Page Offset |
+----------------------+----------------------+----------------------+
*/
/* Page table index (bits 12:21). */
#define PTSHIFT PGBITS /* First page table bit. */
#define PTBITS 10 /* Number of page table bits. */
#define PTSPAN (1 << PTBITS << PGBITS) /* Bytes covered by a page table. */
#define PTMASK BITMASK(PTSHIFT, PTBITS) /* Page table bits (12:21). */
/* Page directory index (bits 22:31). */
#define PDSHIFT (PTSHIFT + PTBITS) /* First page directory bit. */
#define PDBITS 10 /* Number of page dir bits. */
#define PDMASK BITMASK(PDSHIFT, PDBITS) /* Page directory bits (22:31). */
/* Obtains page table index from a virtual address. */
static inline unsigned pt_no (const void *va) {
return ((uintptr_t) va & PTMASK) >> PTSHIFT;
}
/* Obtains page directory index from a virtual address. */
static inline uintptr_t pd_no (const void *va) {
return (uintptr_t) va >> PDSHIFT;
}
/* Page directory and page table entries.
For more information see the section on page tables in the
Pintos reference guide chapter, or [IA32-v3a] 3.7.6
"Page-Directory and Page-Table Entries".
PDEs and PTEs share a common format:
31 12 11 0
+------------------------------------+------------------------+
| Physical Address | Flags |
+------------------------------------+------------------------+
In a PDE, the physical address points to a page table.
In a PTE, the physical address points to a data, or code page.
The important flags are listed below.
When a PDE or PTE is not "present", the other flags are
ignored.
A PDE or PTE that is initialized to 0 will be interpreted as
"not present", which is just fine. */
#define PTE_FLAGS 0x00000fff /* Flag bits. */
#define PTE_ADDR 0xfffff000 /* Address bits. */
#define PTE_AVL 0x00000e00 /* Bits available for OS use. */
#define PTE_P 0x1 /* 1=present, 0=not present. */
#define PTE_W 0x2 /* 1=read/write, 0=read-only. */
#define PTE_U 0x4 /* 1=user/kernel, 0=kernel only. */
#define PTE_A 0x20 /* 1=accessed, 0=not acccessed. */
#define PTE_D 0x40 /* 1=dirty, 0=not dirty (PTEs only). */
/* Returns a PDE that points to page table PT. */
static inline uint32_t pde_create (uint32_t *pt) {
ASSERT (pg_ofs (pt) == 0);
return vtop (pt) | PTE_U | PTE_P | PTE_W;
}
/* Returns a pointer to the page table that page directory entry
PDE, which must "present", points to. */
static inline uint32_t *pde_get_pt (uint32_t pde) {
ASSERT (pde & PTE_P);
return ptov (pde & PTE_ADDR);
}
/* Returns a PTE points to PAGE.
The PTE's page is readable.
If WRITABLE is true then it will be writable as well.
The page will be usable only by ring 0 code (the kernel). */
static inline uint32_t pte_create_kernel (void *page, bool writable) {
ASSERT (pg_ofs (page) == 0);
return vtop (page) | PTE_P | (writable ? PTE_W : 0);
}
/* Returns a PTE that points to PAGE.
The PTE's page is readable.
If WRITABLE is true then it will be writable as well.
The page will be usable by both user and kernel code. */
static inline uint32_t pte_create_user (void *page, bool writable) {
return pte_create_kernel (page, writable) | PTE_U;
}
/* Returns a pointer to the page that page table entry PTE points
to. */
static inline void *pte_get_page (uint32_t pte) {
return ptov (pte & PTE_ADDR);
}
#endif /* threads/pte.h */
| 10cm | trunk/10cm/pintos/src/threads/pte.h | C | oos | 4,075 |
#ifndef THREADS_MALLOC_H
#define THREADS_MALLOC_H
#include <debug.h>
#include <stddef.h>
void malloc_init (void);
void *malloc (size_t) __attribute__ ((malloc));
void *calloc (size_t, size_t) __attribute__ ((malloc));
void *realloc (void *, size_t);
void free (void *);
#endif /* threads/malloc.h */
| 10cm | trunk/10cm/pintos/src/threads/malloc.h | C | oos | 303 |
#ifndef THREADS_PALLOC_H
#define THREADS_PALLOC_H
#include <stddef.h>
/* How to allocate pages. */
enum palloc_flags
{
PAL_ASSERT = 001, /* Panic on failure. */
PAL_ZERO = 002, /* Zero page contents. */
PAL_USER = 004 /* User page. */
};
/* Maximum number of pages to put into user pool. */
extern size_t user_page_limit;
void palloc_init (void);
void *palloc_get_page (enum palloc_flags);
void *palloc_get_multiple (enum palloc_flags, size_t page_cnt);
void palloc_free_page (void *);
void palloc_free_multiple (void *, size_t page_cnt);
#endif /* threads/palloc.h */
| 10cm | trunk/10cm/pintos/src/threads/palloc.h | C | oos | 625 |
include ../Makefile.kernel
| 10cm | trunk/10cm/pintos/src/threads/Makefile | Makefile | oos | 27 |
/* This file is derived from source code for the Nachos
instructional operating system. The Nachos copyright notice
is reproduced in full below. */
/* Copyright (c) 1992-1996 The Regents of the University of California.
All rights reserved.
Permission to use, copy, modify and distribute this software
and its documentation for any purpose, without fee, and
without written agreement is hereby granted, provided that the
above copyright notice and the following two paragraphs appear
in all copies of this software.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO
ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE
AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA
HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
*/
#include "threads/synch.h"
#include <stdio.h>
#include <string.h>
#include "threads/interrupt.h"
#include "threads/thread.h"
/* Initializes semaphore SEMA to VALUE. A semaphore is a
nonnegative integer along with two atomic operators for
manipulating it:
- down or "P": wait for the value to become positive, then
decrement it.
- up or "V": increment the value (and wake up one waiting
thread, if any) */
void
sema_init (struct semaphore *sema, unsigned value)
{
ASSERT (sema != NULL);
sema->value = value;
list_init (&sema->waiters);
}
/* Down or "P" operation on a semaphore. Waits for SEMA's value
to become positive and then atomically decrements it.
This function may sleep, so it must not be called within an
interrupt handler. This function may be called with
interrupts disabled, but if it sleeps then the next scheduled
thread will probably turn interrupts back on. */
void
sema_down (struct semaphore *sema)
{
enum intr_level old_level;
ASSERT (sema != NULL);
ASSERT (!intr_context ());
old_level = intr_disable ();
while (sema->value == 0)
{
list_push_back (&sema->waiters, &thread_current ()->elem);
thread_block ();
}
sema->value--;
intr_set_level (old_level);
}
/* Down or "P" operation on a semaphore, but only if the
semaphore is not already 0. Returns true if the semaphore is
decremented, false otherwise.
This function may be called from an interrupt handler. */
bool
sema_try_down (struct semaphore *sema)
{
enum intr_level old_level;
bool success;
ASSERT (sema != NULL);
old_level = intr_disable ();
if (sema->value > 0)
{
sema->value--;
success = true;
}
else
success = false;
intr_set_level (old_level);
return success;
}
/* Up or "V" operation on a semaphore. Increments SEMA's value
and wakes up one thread of those waiting for SEMA, if any.
This function may be called from an interrupt handler. */
void
sema_up (struct semaphore *sema)
{
enum intr_level old_level;
ASSERT (sema != NULL);
old_level = intr_disable ();
if (!list_empty (&sema->waiters))
thread_unblock (list_entry (list_pop_front (&sema->waiters),
struct thread, elem));
sema->value++;
intr_set_level (old_level);
}
static void sema_test_helper (void *sema_);
/* Self test for semaphores that makes control "ping-pong"
between a pair of threads. Insert calls to printf() to see
what's going on. */
void
sema_self_test (void)
{
struct semaphore sema[2];
int i;
printf ("Testing semaphores...");
sema_init (&sema[0], 0);
sema_init (&sema[1], 0);
thread_create ("sema-test", PRI_DEFAULT, sema_test_helper, &sema);
for (i = 0; i < 10; i++)
{
sema_up (&sema[0]);
sema_down (&sema[1]);
}
printf ("done.\n");
}
/* Thread function used by sema_self_test(). */
static void
sema_test_helper (void *sema_)
{
struct semaphore *sema = sema_;
int i;
for (i = 0; i < 10; i++)
{
sema_down (&sema[0]);
sema_up (&sema[1]);
}
}
/* Initializes LOCK. A lock can be held by at most a single
thread at any given time. Our locks are not "recursive", that
is, it is an error for the thread currently holding a lock to
try to acquire that lock.
A lock is a specialization of a semaphore with an initial
value of 1. The difference between a lock and such a
semaphore is twofold. First, a semaphore can have a value
greater than 1, but a lock can only be owned by a single
thread at one time. Second, a semaphore does not have an owner,
meaning that one thread can "down" the semaphore and then
another one "up" it, but with a lock the same thread must both
acquire and release it. When these restrictions prove
onerous, it's a good sign that a semaphore should be used,
instead of a lock. */
void
lock_init (struct lock *lock)
{
ASSERT (lock != NULL);
lock->holder = NULL;
sema_init (&lock->semaphore, 1);
}
/* Acquires LOCK, sleeping until it becomes available if
necessary. The lock must not already be held by the current
thread.
This function may sleep, so it must not be called within an
interrupt handler. This function may be called with
interrupts disabled, but interrupts will be turned back on if
we need to sleep. */
void
lock_acquire (struct lock *lock)
{
ASSERT (lock != NULL);
ASSERT (!intr_context ());
ASSERT (!lock_held_by_current_thread (lock));
sema_down (&lock->semaphore);
lock->holder = thread_current ();
}
/* Tries to acquires LOCK and returns true if successful or false
on failure. The lock must not already be held by the current
thread.
This function will not sleep, so it may be called within an
interrupt handler. */
bool
lock_try_acquire (struct lock *lock)
{
bool success;
ASSERT (lock != NULL);
ASSERT (!lock_held_by_current_thread (lock));
success = sema_try_down (&lock->semaphore);
if (success)
lock->holder = thread_current ();
return success;
}
/* Releases LOCK, which must be owned by the current thread.
An interrupt handler cann't acquire a lock, so it does not
make sense to try to release a lock within an interrupt
handler. */
void
lock_release (struct lock *lock)
{
ASSERT (lock != NULL);
ASSERT (lock_held_by_current_thread (lock));
lock->holder = NULL;
sema_up (&lock->semaphore);
}
/* Returns true if the current thread holds LOCK, false
otherwise. (Note that testing whether some other thread holds
a lock would be racy.) */
bool
lock_held_by_current_thread (const struct lock *lock)
{
ASSERT (lock != NULL);
return lock->holder == thread_current ();
}
/* One semaphore in a list. */
struct semaphore_elem
{
struct list_elem elem; /* List element. */
struct semaphore semaphore; /* This semaphore. */
};
/* Initializes condition variable "COND". A condition variable
allows one piece of code to signal a condition and cooperating
code to receive the signal and act upon it. */
void
cond_init (struct condition *cond)
{
ASSERT (cond != NULL);
list_init (&cond->waiters);
}
/* Atomically releases LOCK and waits for COND to be signaled by
some other piece of code. After COND is signaled, LOCK is
reacquired before returning. LOCK must be held before calling
this function.
The monitor implemented by this function is "Mesa" style, not
"Hoare" style, that is, sending and receiving a signal are not
an atomic operation. Thus, typically the caller must recheck
the condition after the wait completes and, if necessary, wait
again.
A given condition variable is associated with only a single
lock, but one lock may be associated with any number of
condition variables. That is, there is a one-to-many mapping
from locks to condition variables.
This function may sleep, so it must not be called within an
interrupt handler. This function may be called with
interrupts disabled, but interrupts will be turned back on if
we need to sleep. */
void
cond_wait (struct condition *cond, struct lock *lock)
{
struct semaphore_elem waiter;
ASSERT (cond != NULL);
ASSERT (lock != NULL);
ASSERT (!intr_context ());
ASSERT (lock_held_by_current_thread (lock));
sema_init (&waiter.semaphore, 0);
list_push_back (&cond->waiters, &waiter.elem);
lock_release (lock);
sema_down (&waiter.semaphore);
lock_acquire (lock);
}
/* If any threads are waiting on COND (protected by LOCK), then
this function signals one of them to wake up from its wait.
LOCK must be held before calling this function.
An interrupt handler cannot acquire a lock, so it does not
make sense to try to signal a condition variable within an
interrupt handler. */
void
cond_signal (struct condition *cond, struct lock *lock UNUSED)
{
ASSERT (cond != NULL);
ASSERT (lock != NULL);
ASSERT (!intr_context ());
ASSERT (lock_held_by_current_thread (lock));
if (!list_empty (&cond->waiters))
sema_up (&list_entry (list_pop_front (&cond->waiters),
struct semaphore_elem, elem)->semaphore);
}
/* Wakes up all threads, if any, waiting on COND (protected by
LOCK). LOCK must be held before calling this function.
An interrupt handler cannot acquire a lock, so it does not
make sense to try to signal a condition variable within an
interrupt handler. */
void
cond_broadcast (struct condition *cond, struct lock *lock)
{
ASSERT (cond != NULL);
ASSERT (lock != NULL);
while (!list_empty (&cond->waiters))
cond_signal (cond, lock);
}
| 10cm | trunk/10cm/pintos/src/threads/synch.c | C | oos | 9,879 |
#ifndef THREADS_INTR_STUBS_H
#define THREADS_INTR_STUBS_H
/* Interrupt stubs.
These are little snippets of code in intr-stubs.S, one for
each of the 256 possible x86 interrupts. Each one does a
little bit of stack manipulation, then jumps to intr_entry().
See intr-stubs.S for more information.
This array points to each of the interrupt stub entry points
so that intr_init() can easily find them. */
typedef void intr_stub_func (void);
extern intr_stub_func *intr_stubs[256];
/* Interrupt return path. */
void intr_exit (void);
#endif /* threads/intr-stubs.h */
| 10cm | trunk/10cm/pintos/src/threads/intr-stubs.h | C | oos | 587 |
#ifndef FILESYS_FILESYS_H
#define FILESYS_FILESYS_H
#include <stdbool.h>
#include "filesys/off_t.h"
/* Sectors of system file inodes. */
#define FREE_MAP_SECTOR 0 /* Free map file inode sector. */
#define ROOT_DIR_SECTOR 1 /* Root directory file inode sector. */
/* Disk used for file system. */
extern struct disk *filesys_disk;
void filesys_init (bool format);
void filesys_done (void);
bool filesys_create (const char *name, off_t initial_size);
struct file *filesys_open (const char *name);
bool filesys_remove (const char *name);
#endif /* filesys/filesys.h */
| 10cm | trunk/10cm/pintos/src/filesys/filesys.h | C | oos | 584 |
#ifndef FILESYS_FREE_MAP_H
#define FILESYS_FREE_MAP_H
#include <stdbool.h>
#include <stddef.h>
#include "devices/disk.h"
void free_map_init (void);
void free_map_read (void);
void free_map_create (void);
void free_map_open (void);
void free_map_close (void);
bool free_map_allocate (size_t, disk_sector_t *);
void free_map_release (disk_sector_t, size_t);
#endif /* filesys/free-map.h */
| 10cm | trunk/10cm/pintos/src/filesys/free-map.h | C | oos | 393 |
#include "filesys/cache.h"
#include <stdio.h>
#include <string.h>
#include "filesys/filesys.h"
#include "threads/malloc.h"
#include "threads/thread.h"
#include "devices/timer.h"
struct cache_block* cache_find_block(struct disk *d, disk_sector_t sec_no);
struct cache_block* cache_create_block(struct disk *d, disk_sector_t sec_no, bool read);
void cache_write_back(int64_t current);
static thread_func cache_write_back_thread;
struct list cache_list;
struct cache_block *cache_candidate;
void cache_init(){
list_init(&cache_list);
cache_candidate = NULL;
#ifdef __BUFFER_CACHE_
thread_create("cache_write_back", PRI_DEFAULT, &cache_write_back_thread, NULL);
#endif
}
// cache_write_back을 주기적으로 호출하는 thread 함수
static void cache_write_back_thread(void *aux UNUSED){
while (1){
int64_t current = timer_ticks();
cache_write_back(current);
timer_sleep(100);
}
}
void cache_read_block(struct disk *d, disk_sector_t sec_no, void *buffer){
#ifdef __BUFFER_CACHE_
struct cache_block* b = cache_create_block(d, sec_no, true);
b->accessed = true;
memcpy(buffer, b->buffer, DISK_SECTOR_SIZE);
// read-ahead. 다음 block을 buffer에 올린다.
cache_create_block(d, sec_no + 1, true);
#else
disk_read(d, sec_no, buffer);
#endif
}
void cache_read_bytes(struct disk *d, disk_sector_t sec_no, void *buffer, int sector_ofs, int chunk_size){
struct cache_block* b = cache_create_block(d, sec_no, true);
b->accessed = true;
memcpy(buffer, b->buffer + sector_ofs, chunk_size);
// read-ahead, 다음 block buffer에 올린다.
cache_create_block(d, sec_no + 1, true);
}
void cache_write_block(struct disk *d, disk_sector_t sec_no, const void *buffer){
#ifdef __BUFFER_CACHE_
struct cache_block* b = cache_create_block(d, sec_no, false);
memcpy (b->buffer, buffer, DISK_SECTOR_SIZE);
// dirty 될 때 시간을 저장.
if(b->dirty == false)
{
b->dirty_time = timer_ticks();
}
b->dirty = true;
b->accessed = true;
#else
disk_write(d, sec_no, buffer);
#endif
}
void cache_write_bytes(struct disk *d, disk_sector_t sec_no, const void *buffer, int sector_ofs, int chunk_size){
struct cache_block* b = cache_create_block(d, sec_no, true);
memcpy (b->buffer + sector_ofs, buffer, chunk_size);
// dirty 될 때 시간을 저장.
if(b->dirty == false)
b->dirty_time = timer_ticks();
b->dirty = true;
b->accessed = true;
}
void cache_flush(struct disk *d, disk_sector_t start_sec, disk_sector_t end_sec){
struct list_elem *e;
for (e = list_begin(&cache_list); e != list_end(&cache_list); e
= list_next(e)) {
struct cache_block *b = list_entry (e, struct cache_block, elem);
if (b->d == d && b->sec_no >= start_sec && b->sec_no <= end_sec) {
disk_write(b->d, b->sec_no, b->buffer);
b->dirty = false;
}
}
}
// list 돌면서 dirty block 중에 시간이 오래 된 것이 있으면 write_back 한다.
void cache_write_back(int64_t current)
{
struct list_elem *e;
for (e = list_begin(&cache_list); e != list_end(&cache_list); e
= list_next(e))
{
struct cache_block *b = list_entry (e, struct cache_block, elem);
if( b->dirty && current - b->dirty_time >= 100 ){
disk_write(b->d, b->sec_no, b->buffer);
b->dirty = false;
}
}
}
void cache_release(){
while (!list_empty(&cache_list)){
struct list_elem *e = list_pop_front(&cache_list);
struct cache_block* b = list_entry (e, struct cache_block, elem);
if (b->dirty){
disk_write (b->d, b->sec_no, b->buffer);
}
free(b->buffer);
free(b);
}
cache_candidate = NULL;
}
struct cache_block* cache_create_block(struct disk *d, disk_sector_t sec_no, bool read){
struct cache_block* b = cache_find_block(d, sec_no);
if(b != NULL){
return b;
}
if (list_size(&cache_list) >= 64){
// evict
b = pick_evict_cache();
if (b->dirty) disk_write(b->d, b->sec_no, b->buffer);
} else {
b = malloc(sizeof(struct cache_block));
b->buffer = malloc(DISK_SECTOR_SIZE);
list_push_back(&cache_list, &b->elem);
}
b->d = d;
b->sec_no = sec_no;
b->accessed = false;
if (read){
disk_read (d, sec_no, b->buffer);
b->dirty = false;
} else {
b->dirty = true;
b->dirty_time = timer_ticks();
}
return b;
}
struct cache_block* cache_find_block(struct disk *d, disk_sector_t sec_no){
struct list_elem *e;
for (e = list_begin(&cache_list); e != list_end(&cache_list); e
= list_next(e)) {
struct cache_block *b = list_entry (e, struct cache_block, elem);
if (b->d == d && b->sec_no == sec_no) {
return b;
}
}
return NULL;
}
// cache에서 evict 할 block을 선정하는 함수
struct cache_block* pick_evict_cache()
{
struct list_elem *e;
struct cache_block *to_evict;
// candidate block이 NULL일 경우 list의 가장 처음 원소를 후보로 정한다.
if(cache_candidate == NULL)
{
e = list_begin(&cache_list);
cache_candidate = list_entry(e, struct cache_block, elem);
}
e = &cache_candidate->elem;
// block 이 access되었다면 list의 다음으로 넘어간다.
while( cache_is_accessed(cache_candidate) )
{
cache_set_accessed(cache_candidate, false);
e = list_clock_next(e, &cache_list);
cache_candidate = list_entry(e, struct cache_block, elem);
}
to_evict = cache_candidate;
e = list_clock_next(e, &cache_list);
cache_candidate = list_entry(e, struct cache_block, elem);
return to_evict;
}
// cache가 access 되었는지 return 하는 함수
bool cache_is_accessed(struct cache_block *b)
{
return b->accessed;
}
bool cache_is_dirty(struct cache_block *b)
{
return b->dirty;
}
// cache 의 accessed 를 ACCESSED로 set
void cache_set_accessed(struct cache_block *b, bool accessed)
{
b->accessed = accessed;
}
| 10cm | trunk/10cm/pintos/src/filesys/cache.c | C | oos | 5,636 |
#ifndef FILESYS_FILE_H
#define FILESYS_FILE_H
#include "filesys/off_t.h"
struct inode;
/* Opening and closing files. */
struct file *file_open (struct inode *);
struct file *file_reopen (struct file *);
void file_close (struct file *);
struct inode *file_get_inode (struct file *);
/* Reading and writing. */
off_t file_read (struct file *, void *, off_t);
off_t file_read_at (struct file *, void *, off_t size, off_t start);
off_t file_write (struct file *, const void *, off_t);
off_t file_write_at (struct file *, const void *, off_t size, off_t start);
/* Preventing writes. */
void file_deny_write (struct file *);
void file_allow_write (struct file *);
/* File position. */
void file_seek (struct file *, off_t);
off_t file_tell (struct file *);
off_t file_length (struct file *);
#endif /* filesys/file.h */
| 10cm | trunk/10cm/pintos/src/filesys/file.h | C | oos | 823 |
#ifndef FILESYS_INODE_H
#define FILESYS_INODE_H
#include <stdbool.h>
#include "filesys/off_t.h"
#include "devices/disk.h"
struct bitmap;
void inode_init (void);
bool inode_create (disk_sector_t, off_t);
struct inode *inode_open (disk_sector_t);
struct inode *inode_reopen (struct inode *);
disk_sector_t inode_get_inumber (const struct inode *);
void inode_close (struct inode *);
void inode_remove (struct inode *);
off_t inode_read_at (struct inode *, void *, off_t size, off_t offset);
off_t inode_write_at (struct inode *, const void *, off_t size, off_t offset);
void inode_deny_write (struct inode *);
void inode_allow_write (struct inode *);
off_t inode_length (const struct inode *);
#endif /* filesys/inode.h */
| 10cm | trunk/10cm/pintos/src/filesys/inode.h | C | oos | 726 |
# -*- makefile -*-
os.dsk: DEFINES = -DUSERPROG -DFILESYS
KERNEL_SUBDIRS = threads devices lib lib/kernel userprog filesys
TEST_SUBDIRS = tests/userprog tests/filesys/base tests/filesys/extended
GRADING_FILE = $(SRCDIR)/tests/filesys/Grading.no-vm
SIMULATOR = --qemu
#Uncomment the lines below to enable VM.
os.dsk: DEFINES += -DVM
KERNEL_SUBDIRS += vm
TEST_SUBDIRS += tests/vm
GRADING_FILE = $(SRCDIR)/tests/filesys/Grading.with-vm
| 10cm | trunk/10cm/pintos/src/filesys/Make.vars | Makefile | oos | 435 |
#ifndef FILESYS_OFF_T_H
#define FILESYS_OFF_T_H
#include <stdint.h>
/* An offset within a file.
This is a separate header because multiple headers want this
definition but not any others. */
typedef int32_t off_t;
/* Format specifier for printf(), e.g.:
printf ("offset=%"PROTd"\n", offset); */
#define PROTd PRId32
#endif /* filesys/off_t.h */
| 10cm | trunk/10cm/pintos/src/filesys/off_t.h | C | oos | 358 |
#include "filesys/file.h"
#include <debug.h>
#include "filesys/inode.h"
#include "threads/malloc.h"
/* An open file. */
struct file
{
struct inode *inode; /* File inode. */
off_t pos; /* Current position. */
bool deny_write; /* Has file_deny_write() been called? */
};
/* Open a file for the given INODE, of which it takes ownership,
and returns the new file. Returns a null pointer if an
allocation fails or if INODE is null. */
struct file *
file_open (struct inode *inode)
{
struct file *file = calloc (1, sizeof *file);
if (inode != NULL && file != NULL)
{
file->inode = inode;
file->pos = 0;
file->deny_write = false;
return file;
}
else
{
inode_close (inode);
free (file);
return NULL;
}
}
/* Opens and returns a new file for the same inode as FILE.
Returns a null pointer if unsuccessful. */
struct file *
file_reopen (struct file *file)
{
return file_open (inode_reopen (file->inode));
}
/* Closes FILE. */
void
file_close (struct file *file)
{
if (file != NULL)
{
file_allow_write (file);
inode_close (file->inode);
free (file);
}
}
/* Returns the inode encapsulated by FILE. */
struct inode *
file_get_inode (struct file *file)
{
return file->inode;
}
/* Reads SIZE bytes from FILE into BUFFER,
starting at the file's current position.
Returns the number of bytes actually read,
which may be less than SIZE if end-of-file is reached.
Advances FILE's position by the number of bytes read. */
off_t
file_read (struct file *file, void *buffer, off_t size)
{
off_t bytes_read = inode_read_at (file->inode, buffer, size, file->pos);
file->pos += bytes_read;
return bytes_read;
}
/* Reads SIZE bytes from FILE into BUFFER,
starting at offset FILE_OFS in the file.
Returns the number of bytes actually read,
which may be less than SIZE if end of file is reached.
The file's current position is unaffected. */
off_t
file_read_at (struct file *file, void *buffer, off_t size, off_t file_ofs)
{
return inode_read_at (file->inode, buffer, size, file_ofs);
}
/* Writes SIZE bytes from BUFFER into FILE,
starting at the file's current position.
Returns the number of bytes actually written,
which may be less than SIZE if end of file is reached.
(Normally, we'd grow the file in that case, but file growth is
not yet implemented.)
Advances FILE's position by the number of bytes read. */
off_t
file_write (struct file *file, const void *buffer, off_t size)
{
off_t bytes_written = inode_write_at (file->inode, buffer, size, file->pos);
file->pos += bytes_written;
return bytes_written;
}
/* Writes SIZE bytes from BUFFER into FILE,
starting at offset FILE_OFS in the file.
Returns the number of bytes actually written,
which may be less than SIZE if end of file is reached.
(Normally we'd grow the file in that case, but file growth is
not yet implemented.)
The file's current position is unaffected. */
off_t
file_write_at (struct file *file, const void *buffer, off_t size,
off_t file_ofs)
{
return inode_write_at (file->inode, buffer, size, file_ofs);
}
/* Prevents write operations on FILE's underlying inode
until file_allow_write() is called or FILE is closed. */
void
file_deny_write (struct file *file)
{
ASSERT (file != NULL);
if (!file->deny_write)
{
file->deny_write = true;
inode_deny_write (file->inode);
}
}
/* Re-enables write operations on FILE's underlying inode.
(Writes might still be denied by some other file that has the
same inode open.) */
void
file_allow_write (struct file *file)
{
ASSERT (file != NULL);
if (file->deny_write)
{
file->deny_write = false;
inode_allow_write (file->inode);
}
}
/* Returns the size of FILE in bytes. */
off_t
file_length (struct file *file)
{
ASSERT (file != NULL);
return inode_length (file->inode);
}
/* Sets the current position in FILE to NEW_POS bytes from the
start of file. */
void
file_seek (struct file *file, off_t new_pos)
{
ASSERT (file != NULL);
ASSERT (new_pos >= 0);
file->pos = new_pos;
}
/* Returns the current position in FILE as a byte offset from the
start of the file. */
off_t
file_tell (struct file *file)
{
ASSERT (file != NULL);
return file->pos;
}
| 10cm | trunk/10cm/pintos/src/filesys/file.c | C | oos | 4,383 |
#include "filesys/fsutil.h"
#include <debug.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ustar.h>
#include "filesys/directory.h"
#include "filesys/file.h"
#include "filesys/filesys.h"
#include "filesys/cache.h"
#include "devices/disk.h"
#include "threads/malloc.h"
#include "threads/palloc.h"
#include "threads/vaddr.h"
/* Lists files in the root directory. */
void
fsutil_ls (char **argv UNUSED)
{
struct dir *dir;
char name[NAME_MAX + 1];
printf ("Files in the root directory:\n");
dir = dir_open_root ();
if (dir == NULL)
PANIC ("root dir open failed");
while (dir_readdir (dir, name))
printf ("%s\n", name);
printf ("End of listing.\n");
}
/* Prints the contents of file ARGV[1] to the system console as
hex and ASCII. */
void
fsutil_cat (char **argv)
{
const char *file_name = argv[1];
struct file *file;
char *buffer;
printf ("Printing '%s' to the console...\n", file_name);
file = filesys_open (file_name);
if (file == NULL)
PANIC ("%s: open failed", file_name);
buffer = palloc_get_page (PAL_ASSERT);
for (;;)
{
off_t pos = file_tell (file);
off_t n = file_read (file, buffer, PGSIZE);
if (n == 0)
break;
hex_dump (pos, buffer, n, true);
}
palloc_free_page (buffer);
file_close (file);
}
/* Deletes file ARGV[1]. */
void
fsutil_rm (char **argv)
{
const char *file_name = argv[1];
printf ("Deleting '%s'...\n", file_name);
if (!filesys_remove (file_name))
PANIC ("%s: delete failed\n", file_name);
}
/* Extracts a ustar format tar archive from the scratch disk, hdc
or hd1:0, into the Pintos file system. */
void
fsutil_extract (char **argv UNUSED)
{
static disk_sector_t sector = 0;
struct disk *src;
void *header, *data;
/* Allocate buffers. */
header = malloc (DISK_SECTOR_SIZE);
data = malloc (DISK_SECTOR_SIZE);
if (header == NULL || data == NULL)
PANIC ("couldn't allocate buffers");
/* Open source disk. */
src = disk_get (1, 0);
if (src == NULL)
PANIC ("couldn't open scratch disk (hdc or hd1:0)");
printf ("Extracting ustar archive from scratch disk into file system...\n");
for (;;)
{
const char *file_name;
const char *error;
enum ustar_type type;
int size;
/* Read and parse ustar header. */
cache_read_block (src, sector++, header);
error = ustar_parse_header (header, &file_name, &type, &size);
if (error != NULL)
PANIC ("bad ustar header in sector %"PRDSNu" (%s)", sector - 1, error);
if (type == USTAR_EOF)
{
/* End of archive. */
break;
}
else if (type == USTAR_DIRECTORY)
printf ("ignoring directory %s\n", file_name);
else if (type == USTAR_REGULAR)
{
struct file *dst;
printf ("Putting '%s' into the file system...\n", file_name);
/* Create destination file. */
if (!filesys_create (file_name, size))
PANIC ("%s: create failed", file_name);
dst = filesys_open (file_name);
if (dst == NULL)
PANIC ("%s: open failed", file_name);
/* Do copy. */
while (size > 0)
{
int chunk_size = (size > DISK_SECTOR_SIZE
? DISK_SECTOR_SIZE
: size);
cache_read_block (src, sector++, data);
if (file_write (dst, data, chunk_size) != chunk_size)
PANIC ("%s: write failed with %d bytes unwritten",
file_name, size);
size -= chunk_size;
}
/* Finish up. */
file_close (dst);
}
}
/* Erase the ustar header from the start of the disk, so that
the extraction operation is idempotent. We erase two blocks
because two blocks of zeros are the ustar end of archive
marker. */
printf ("Erasing ustar archive...\n");
memset (header, 0, DISK_SECTOR_SIZE);
cache_write_block (src, 0, header);
cache_write_block (src, 1, header);
free (data);
free (header);
}
/* Copies file FILE_NAME from the file system to the scratch
disk, in ustar format.
The first call to this function will write starting at the
beginning of the scratch disk. Later calls advance across the
disk. This position is independent of that used for
fsutil_extract(), so `extract' should precede all
`append's. */
void
fsutil_append (char **argv)
{
static disk_sector_t sector = 0;
const char *file_name = argv[1];
void *buffer;
struct file *src;
struct disk *dst;
off_t size;
printf ("Appending '%s' to ustar archive on scratch disk...\n", file_name);
/* Allocate buffer. */
buffer = malloc (DISK_SECTOR_SIZE);
if (buffer == NULL)
PANIC ("couldn't allocate buffer");
/* Open source file. */
src = filesys_open (file_name);
if (src == NULL)
PANIC ("%s: open failed", file_name);
size = file_length (src);
/* Open target disk. */
dst = disk_get (1, 0);
if (dst == NULL)
PANIC ("couldn't open target disk (hdc or hd1:0)");
/* Write ustar header to first sector. */
if (!ustar_make_header (file_name, USTAR_REGULAR, size, buffer))
PANIC ("%s: name too long for ustar format", file_name);
cache_write_block (dst, sector++, buffer);
/* Do copy. */
while (size > 0)
{
int chunk_size = size > DISK_SECTOR_SIZE ? DISK_SECTOR_SIZE : size;
if (sector >= disk_size (dst))
PANIC ("%s: out of space on scratch disk", file_name);
if (file_read (src, buffer, chunk_size) != chunk_size)
PANIC ("%s: read failed with %"PROTd" bytes unread", file_name, size);
memset (buffer + chunk_size, 0, DISK_SECTOR_SIZE - chunk_size);
cache_write_block (dst, sector++, buffer);
size -= chunk_size;
}
/* Write ustar end-of-archive marker, which is two consecutive
sectors full of zeros. Don't advance our position past
them, though, in case you have more files to append. */
memset (buffer, 0, DISK_SECTOR_SIZE);
cache_write_block (dst, sector, buffer);
cache_write_block (dst, sector, buffer + 1);
/* Finish up. */
file_close (src);
free (buffer);
}
| 10cm | trunk/10cm/pintos/src/filesys/fsutil.c | C | oos | 6,232 |
#ifndef FILESYS_DIRECTORY_H
#define FILESYS_DIRECTORY_H
#include <stdbool.h>
#include <stddef.h>
#include "devices/disk.h"
/* Maximum length of a file name component.
This is the traditional UNIX maximum length.
After directories are implemented, this maximum length may be
retained, but much longer full path names must be allowed to use. */
#define NAME_MAX 14
struct inode;
/* Opening and closing directories. */
bool dir_create (disk_sector_t sector, size_t entry_cnt);
struct dir *dir_open (struct inode *);
struct dir *dir_open_root (void);
struct dir *dir_reopen (struct dir *);
void dir_close (struct dir *);
struct inode *dir_get_inode (struct dir *);
/* Reading and writing. */
bool dir_lookup (const struct dir *, const char *name, struct inode **);
bool dir_add (struct dir *, const char *name, disk_sector_t);
bool dir_remove (struct dir *, const char *name);
bool dir_readdir (struct dir *, char name[NAME_MAX + 1]);
#endif /* filesys/directory.h */
| 10cm | trunk/10cm/pintos/src/filesys/directory.h | C | oos | 980 |
# -*- makefile -*-
os.dsk: DEFINES = -DUSERPROG -DFILESYS
KERNEL_SUBDIRS = threads devices lib lib/kernel userprog filesys
TEST_SUBDIRS = tests/userprog tests/filesys/base tests/filesys/extended
GRADING_FILE = $(SRCDIR)/tests/filesys/Grading.no-vm
SIMULATOR = --qemu
#Uncomment the lines below to enable VM.
os.dsk: DEFINES += -DVM
KERNEL_SUBDIRS += vm
TEST_SUBDIRS += tests/vm
GRADING_FILE = $(SRCDIR)/tests/filesys/Grading.with-vm
| 10cm | trunk/10cm/pintos/src/filesys/.svn/text-base/Make.vars.svn-base | Makefile | oos | 435 |
#include "filesys/inode.h"
#include <list.h>
#include <debug.h>
#include <round.h>
#include <string.h>
#include "filesys/filesys.h"
#include "filesys/free-map.h"
#include "filesys/cache.h"
#include "threads/malloc.h"
/* Identifies an inode. */
#define INODE_MAGIC 0x494e4f44
/* On-disk inode.
It must be exactly DISK_SECTOR_SIZE bytes long. */
struct inode_disk
{
disk_sector_t start; /* First data sector. */
off_t length; /* File size in bytes. */
unsigned magic; /* Magic number. */
uint32_t unused[125]; /* Not used. */
};
/* Returns the number of sectors to allocate for an inode SIZE
bytes long. */
static inline size_t
bytes_to_sectors (off_t size)
{
return DIV_ROUND_UP (size, DISK_SECTOR_SIZE);
}
/* In-memory inode. */
struct inode
{
struct list_elem elem; /* Element in inode list. */
disk_sector_t sector; /* Sector number of disk location. */
int open_cnt; /* Number of openers. */
bool removed; /* True if deleted, false otherwise. */
int deny_write_cnt; /* 0: writes ok, >0: deny writes. */
struct inode_disk data; /* Inode content. */
};
/* Returns the disk sector that contains byte offset POS within
INODE.
Returns -1 if INODE does not contain data for a byte at offset
POS. */
static disk_sector_t
byte_to_sector (const struct inode *inode, off_t pos)
{
ASSERT (inode != NULL);
if (pos < inode->data.length)
return inode->data.start + pos / DISK_SECTOR_SIZE;
else
return -1;
}
/* List of open inodes, so that opening a single inode twice
returns the same `struct inode'. */
static struct list open_inodes;
/* Initializes the inode module. */
void
inode_init (void)
{
list_init (&open_inodes);
}
/* Initializes an inode with LENGTH bytes of data and
writes the new inode to sector SECTOR on the file system
disk.
Returns true if successful.
Returns false if memory or disk allocation fails. */
bool
inode_create (disk_sector_t sector, off_t length)
{
struct inode_disk *disk_inode = NULL;
bool success = false;
ASSERT (length >= 0);
/* If this assertion fails, the inode structure is not exactly
one sector in size, and you should fix it. */
ASSERT (sizeof *disk_inode == DISK_SECTOR_SIZE);
disk_inode = calloc (1, sizeof *disk_inode);
if (disk_inode != NULL)
{
size_t sectors = bytes_to_sectors (length);
disk_inode->length = length;
disk_inode->magic = INODE_MAGIC;
if (free_map_allocate (sectors, &disk_inode->start))
{
cache_write_block (filesys_disk, sector, disk_inode);
if (sectors > 0)
{
static char zeros[DISK_SECTOR_SIZE];
size_t i;
for (i = 0; i < sectors; i++)
cache_write_block (filesys_disk, disk_inode->start + i, zeros);
}
success = true;
}
free (disk_inode);
}
return success;
}
/* Reads an inode from SECTOR
and returns a `struct inode' which contains it.
Returns a null pointer if memory allocation fails. */
struct inode *
inode_open (disk_sector_t sector)
{
struct list_elem *e;
struct inode *inode;
/* Check whether this inode is already open. */
for (e = list_begin (&open_inodes); e != list_end (&open_inodes);
e = list_next (e))
{
inode = list_entry (e, struct inode, elem);
if (inode->sector == sector)
{
inode_reopen (inode);
return inode;
}
}
/* Allocate memory. */
inode = malloc (sizeof *inode);
if (inode == NULL)
return NULL;
/* Initialize. */
list_push_front (&open_inodes, &inode->elem);
inode->sector = sector;
inode->open_cnt = 1;
inode->deny_write_cnt = 0;
inode->removed = false;
cache_read_block (filesys_disk, inode->sector, &inode->data);
return inode;
}
/* Reopens and returns INODE. */
struct inode *
inode_reopen (struct inode *inode)
{
if (inode != NULL)
inode->open_cnt++;
return inode;
}
/* Returns INODE's inode number. */
disk_sector_t
inode_get_inumber (const struct inode *inode)
{
return inode->sector;
}
/* Closes INODE and writes it to disk.
If this was the last reference to INODE, frees its memory.
If INODE was also a removed inode, frees its blocks. */
void
inode_close (struct inode *inode)
{
/* Ignore null pointer. */
if (inode == NULL)
return;
/* Release resources if that was the last opener. */
if (--inode->open_cnt == 0)
{
#ifdef __BUFFER_CACHE_
disk_sector_t sec_start = inode->data.start;
disk_sector_t sec_end = sec_start + inode->data.length;
sec_start = sec_start - sec_start%DISK_SECTOR_SIZE;
cache_flush(filesys_disk, sec_start, sec_end);
#endif
/* Remove from inode list and release lock. */
list_remove (&inode->elem);
/* Deallocate blocks if removed. */
if (inode->removed)
{
free_map_release (inode->sector, 1);
free_map_release (inode->data.start,
bytes_to_sectors (inode->data.length));
}
free (inode);
}
}
/* Marks INODE to be deleted when it is closed by the last caller who
has it open. */
void
inode_remove (struct inode *inode)
{
ASSERT (inode != NULL);
inode->removed = true;
}
/* Reads SIZE bytes from INODE into BUFFER, starting at position OFFSET.
Returns the number of bytes actually read, which may be less
than SIZE if an error occurs or end of file is reached. */
off_t
inode_read_at (struct inode *inode, void *buffer_, off_t size, off_t offset)
{
uint8_t *buffer = buffer_;
off_t bytes_read = 0;
uint8_t *bounce = NULL;
while (size > 0)
{
/* Disk sector to read, starting byte offset within sector. */
disk_sector_t sector_idx = byte_to_sector (inode, offset);
int sector_ofs = offset % DISK_SECTOR_SIZE;
/* Bytes left in inode, bytes left in sector, lesser of the two. */
off_t inode_left = inode_length (inode) - offset;
int sector_left = DISK_SECTOR_SIZE - sector_ofs;
int min_left = inode_left < sector_left ? inode_left : sector_left;
/* Number of bytes to actually copy out of this sector. */
int chunk_size = size < min_left ? size : min_left;
if (chunk_size <= 0)
break;
if (sector_ofs == 0 && chunk_size == DISK_SECTOR_SIZE)
{
/* Read full sector directly into caller's buffer. */
cache_read_block(filesys_disk, sector_idx, buffer + bytes_read);
}
else
{
#ifdef __BUFFER_CACHE_
cache_read_bytes(filesys_disk, sector_idx, buffer + bytes_read, sector_ofs, chunk_size);
#else
/* Read sector into bounce buffer, then partially copy
into caller's buffer. */
if (bounce == NULL)
{
bounce = malloc (DISK_SECTOR_SIZE);
if (bounce == NULL)
break;
}
disk_read (filesys_disk, sector_idx, bounce);
memcpy (buffer + bytes_read, bounce + sector_ofs, chunk_size);
#endif
}
/* Advance. */
size -= chunk_size;
offset += chunk_size;
bytes_read += chunk_size;
}
if (bounce != NULL) free (bounce);
return bytes_read;
}
/* Writes SIZE bytes from BUFFER into INODE, starting at OFFSET.
Returns the number of bytes actually written, which may be
less than SIZE if end of file is reached or an error occurs.
(Normally a write at end of file would extend the inode, but
growth is not yet implemented) */
off_t
inode_write_at (struct inode *inode, const void *buffer_, off_t size,
off_t offset)
{
const uint8_t *buffer = buffer_;
off_t bytes_written = 0;
uint8_t *bounce = NULL;
if (inode->deny_write_cnt)
return 0;
while (size > 0)
{
/* Sector to write, starting byte offset within sector. */
disk_sector_t sector_idx = byte_to_sector (inode, offset);
int sector_ofs = offset % DISK_SECTOR_SIZE;
/* Bytes left in inode, bytes left in sector, lesser of the two. */
off_t inode_left = inode_length (inode) - offset;
int sector_left = DISK_SECTOR_SIZE - sector_ofs;
int min_left = inode_left < sector_left ? inode_left : sector_left;
/* Number of bytes to actually write into this sector. */
int chunk_size = size < min_left ? size : min_left;
if (chunk_size <= 0)
break;
if (sector_ofs == 0 && chunk_size == DISK_SECTOR_SIZE)
{
/* Write full sector directly to disk. */
cache_write_block(filesys_disk, sector_idx, buffer + bytes_written);
}
else
{
/* We need a bounce buffer. */
#ifdef __BUFFER_CACHE_
cache_write_bytes(filesys_disk, sector_idx, buffer + bytes_written, sector_ofs, chunk_size);
#else
if (bounce == NULL)
{
bounce = malloc (DISK_SECTOR_SIZE);
if (bounce == NULL)
break;
}
/* If the sector contains data before or after the chunk
we're writing, then we need to read in the sector
first. Otherwise we start with a sector of all zeros. */
if (sector_ofs > 0 || chunk_size < sector_left)
cache_read_block (filesys_disk, sector_idx, bounce);
else
memset (bounce, 0, DISK_SECTOR_SIZE);
memcpy (bounce + sector_ofs, buffer + bytes_written, chunk_size);
disk_write (filesys_disk, sector_idx, bounce);
#endif
}
/* Advance. */
size -= chunk_size;
offset += chunk_size;
bytes_written += chunk_size;
}
if (bounce != NULL) free (bounce);
return bytes_written;
}
/* Disables writes to INODE.
May be called at most once per inode opener. */
void
inode_deny_write (struct inode *inode)
{
inode->deny_write_cnt++;
ASSERT (inode->deny_write_cnt <= inode->open_cnt);
}
/* Re-enables writes to INODE.
This must be called once by each inode opener who has called
inode_deny_write() on the inode, before closing the inode. */
void
inode_allow_write (struct inode *inode)
{
ASSERT (inode->deny_write_cnt > 0);
ASSERT (inode->deny_write_cnt <= inode->open_cnt);
inode->deny_write_cnt--;
}
/* Returns the length, in bytes, of INODE's data. */
off_t
inode_length (const struct inode *inode)
{
return inode->data.length;
}
| 10cm | trunk/10cm/pintos/src/filesys/inode.c | C | oos | 10,531 |
#ifndef FILESYS_CACHE_H
#define FILESYS_CACHE_H
#include <list.h>
#include "devices/disk.h"
#define __BUFFER_CACHE_
void cache_init(void);
void cache_read_block(struct disk *d, disk_sector_t sec_no, void *buffer);
void cache_read_bytes(struct disk *d, disk_sector_t sec_no, void *buffer, int sector_ofs, int chunk_size);
void cache_write_block(struct disk *d, disk_sector_t sec_no, const void *buffer);
void cache_write_bytes(struct disk *d, disk_sector_t sec_no, const void *buffer, int sector_ofs, int chunk_size);
void cache_flush(struct disk *d, disk_sector_t start_sec, disk_sector_t end_sec);
void cache_release(void);
struct cache_block{
struct disk *d;
disk_sector_t sec_no;
void* buffer;
bool dirty;
bool accessed;
int64_t dirty_time;
struct list_elem elem;
};
bool cache_is_accessed(struct cache_block*);
bool cache_is_dirty(struct cache_block*);
void cache_set_accessed(struct cache_block*, bool);
struct cache_block * pick_evict_cache(void);
#endif /* FILESYS_CACHE_H */
| 10cm | trunk/10cm/pintos/src/filesys/cache.h | C | oos | 999 |