Răsfoiți Sursa

Add format size option and robust disk formatting

Johannes Zellner 2 săptămâni în urmă
părinte
comite
ced98f7fcd
12 a modificat fișierele cu 630 adăugiri și 123 ștergeri
  1. 41 10
      ahci.c
  2. 3 0
      ahci.h
  3. 261 63
      ata.c
  4. 4 0
      ata.h
  5. 11 0
      blkdev.c
  6. 3 0
      blkdev.h
  7. 126 27
      fatformat.c
  8. 7 1
      fatformat.h
  9. 152 6
      format.c
  10. 2 16
      terminal.c
  11. 5 0
      tty.c
  12. 15 0
      vfs.c

+ 41 - 10
ahci.c

@@ -313,7 +313,7 @@ static int ahci_issue(unsigned int port, const unsigned char fis[20], int write,
 {
 {
 	unsigned int *hdr = (unsigned int *)ahci.cl;
 	unsigned int *hdr = (unsigned int *)ahci.cl;
 	unsigned char *ct = (unsigned char *)ahci.ct;
 	unsigned char *ct = (unsigned char *)ahci.ct;
-	unsigned int t0, i;
+	unsigned int t0, i, prdtl = bytes ? 1u : 0u;
 
 
 	/* Wait for the port to be idle (previous command finished). */
 	/* Wait for the port to be idle (previous command finished). */
 	t0 = get_ticks_ms();
 	t0 = get_ticks_ms();
@@ -328,14 +328,16 @@ static int ahci_issue(unsigned int port, const unsigned char fis[20], int write,
 		ct[i] = 0;
 		ct[i] = 0;
 	for (i = 0; i < 20; i++)
 	for (i = 0; i < 20; i++)
 		ct[i] = fis[i];
 		ct[i] = fis[i];
-	/* PRDT entry 0: data buffer + byte count. */
-	((unsigned int *)(ct + 0x80))[0] = dma_addr;
-	((unsigned int *)(ct + 0x80))[1] = 0;
-	((unsigned int *)(ct + 0x80))[2] = 0;
-	((unsigned int *)(ct + 0x80))[3] = ((bytes - 1) & 0x3FFFFFu) | 0x80000000u;
-
-	/* Command header: CFL=5 dwords, W (write), PRDTL=1. */
-	hdr[0] = 5u | (write ? (1u << 6) : 0) | (1u << 16);
+	/* PRDT entry 0: data buffer + byte count (no data: PRDTL = 0). */
+	if (prdtl) {
+		((unsigned int *)(ct + 0x80))[0] = dma_addr;
+		((unsigned int *)(ct + 0x80))[1] = 0;
+		((unsigned int *)(ct + 0x80))[2] = 0;
+		((unsigned int *)(ct + 0x80))[3] = ((bytes - 1) & 0x3FFFFFu) | 0x80000000u;
+	}
+
+	/* Command header: CFL=5 dwords, W (write), PRDTL. */
+	hdr[0] = 5u | (write ? (1u << 6) : 0) | (prdtl << 16);
 	hdr[1] = 0;
 	hdr[1] = 0;
 	hdr[2] = ahci.ct;
 	hdr[2] = ahci.ct;
 	hdr[3] = 0;
 	hdr[3] = 0;
@@ -426,8 +428,22 @@ static int ahci_xfer(unsigned int port, unsigned int lba, void *buf,
 
 
 		if (write)
 		if (write)
 			mem_copy(bounce, p + done * 512u, chunk * 512u);
 			mem_copy(bounce, p + done * 512u, chunk * 512u);
-		if (ahci_issue(port, fis, write, ahci.bounce, chunk * 512u) != 0)
+		if (ahci_issue(port, fis, write, ahci.bounce, chunk * 512u) != 0) {
+			serial_puts(SERIAL_COM1, "ahci: ");
+			serial_puts(SERIAL_COM1, write ? "write" : "read");
+			serial_puts(SERIAL_COM1, " failed port ");
+			serial_putdec(SERIAL_COM1, port);
+			serial_puts(SERIAL_COM1, " lba ");
+			serial_putdec(SERIAL_COM1, cur);
+			serial_puts(SERIAL_COM1, " count ");
+			serial_putdec(SERIAL_COM1, chunk);
+			serial_puts(SERIAL_COM1, " tfd ");
+			serial_puthex(SERIAL_COM1, prd(port, P_TFD));
+			serial_puts(SERIAL_COM1, " is ");
+			serial_puthex(SERIAL_COM1, prd(port, P_IS));
+			serial_putc(SERIAL_COM1, '\n');
 			return -1;
 			return -1;
+		}
 		if (!write)
 		if (!write)
 			mem_copy(p + done * 512u, bounce, chunk * 512u);
 			mem_copy(p + done * 512u, bounce, chunk * 512u);
 		done += chunk;
 		done += chunk;
@@ -446,6 +462,21 @@ int ahci_write_sectors(unsigned int port, unsigned int lba, const void *buf,
 	return ahci_xfer(port, lba, (void *)buf, count, 1);
 	return ahci_xfer(port, lba, (void *)buf, count, 1);
 }
 }
 
 
+int ahci_flush(unsigned int port)
+{
+	unsigned char fis[20];
+	unsigned int i;
+
+	if (!ahci.ok || port >= ahci.nports)
+		return -1;
+	for (i = 0; i < 20; i++)
+		fis[i] = 0;
+	fis[0] = FIS_H2D;
+	fis[1] = FIS_C;
+	fis[2] = 0xEA;                 /* FLUSH CACHE EXT */
+	return ahci_issue(port, fis, 0, 0, 0);
+}
+
 unsigned int ahci_scan(struct ahci_disk *out, unsigned int max)
 unsigned int ahci_scan(struct ahci_disk *out, unsigned int max)
 {
 {
 	unsigned int port, n = 0;
 	unsigned int port, n = 0;

+ 3 - 0
ahci.h

@@ -28,4 +28,7 @@ unsigned int ahci_scan(struct ahci_disk *out, unsigned int max);
 int ahci_read_sectors(unsigned int port, unsigned int lba, void *buf, unsigned int count);
 int ahci_read_sectors(unsigned int port, unsigned int lba, void *buf, unsigned int count);
 int ahci_write_sectors(unsigned int port, unsigned int lba, const void *buf, unsigned int count);
 int ahci_write_sectors(unsigned int port, unsigned int lba, const void *buf, unsigned int count);
 
 
+/* Flush the port's write cache (FLUSH CACHE EXT). */
+int ahci_flush(unsigned int port);
+
 #endif
 #endif

+ 261 - 63
ata.c

@@ -11,8 +11,17 @@
 #include "timer.h"
 #include "timer.h"
 
 
 static unsigned short ata_base[2] = { 0x1F0, 0x170 };
 static unsigned short ata_base[2] = { 0x1F0, 0x170 };
+/* Kept for the bring-up log only; transfers poll the command-block status
+ * because some controllers' alt-status BAR does not answer correctly. */
 static unsigned short ata_ctrl[2] = { 0x3F6, 0x376 };
 static unsigned short ata_ctrl[2] = { 0x3F6, 0x376 };
 
 
+/* Set when a multi-sector PIO command left DRQ pending on this channel.
+ * From then on use one ATA command per sector; slower, but it works on
+ * bridges that mishandle multi-sector PIO. */
+static int ata_single[2];
+static int ata_lba48[2];
+static int ata_tf_logged;
+
 /* Register offsets from the I/O base. */
 /* Register offsets from the I/O base. */
 #define REG_DATA    0
 #define REG_DATA    0
 #define REG_ERROR   1
 #define REG_ERROR   1
@@ -36,6 +45,16 @@ static unsigned short ata_ctrl[2] = { 0x3F6, 0x376 };
 #define CMD_READ_EXT  0x24   /* LBA48 */
 #define CMD_READ_EXT  0x24   /* LBA48 */
 #define CMD_WRITE_EXT 0x34   /* LBA48 */
 #define CMD_WRITE_EXT 0x34   /* LBA48 */
 
 
+/* A spun-down disk can take several seconds to accept its first command;
+ * keep a generous poll budget. */
+#define ATA_TIMEOUT_MS 15000
+
+/* Once the data is transferred, the drive should finish the sector quickly.
+ * A longer wait here would only delay the single-sector fallback. */
+#define ATA_COMPLETE_TIMEOUT_MS 2000
+
+static void ata_reset_channel(unsigned short base, unsigned short ctrl);
+
 /* Point the primary/secondary channels at the PCI IDE interface's native
 /* Point the primary/secondary channels at the PCI IDE interface's native
  * per-channel I/O BARs when it uses native mode, keeping the legacy ports
  * per-channel I/O BARs when it uses native mode, keeping the legacy ports
  * otherwise.  Runs once; without a PCI IDE function the defaults stay. */
  * otherwise.  Runs once; without a PCI IDE function the defaults stay. */
@@ -82,9 +101,12 @@ void ata_init_ports(void)
 				/* prog-if bit 0/2: primary/secondary native mode. */
 				/* prog-if bit 0/2: primary/secondary native mode. */
 				if ((prog & 0x01u) && (bar0 & 0x1u)) {
 				if ((prog & 0x01u) && (bar0 & 0x1u)) {
 					b0 = (unsigned short)(bar0 & 0xFFFCu);
 					b0 = (unsigned short)(bar0 & 0xFFFCu);
+					/* A native-mode BAR1 of 0 is malformed;
+					 * the legacy control port is a safer
+					 * fallback than b0+8. */
 					c0 = (bar1 & 0x1u)
 					c0 = (bar1 & 0x1u)
 						? (unsigned short)(bar1 & 0xFFFCu)
 						? (unsigned short)(bar1 & 0xFFFCu)
-						: (unsigned short)(b0 + 8);
+						: (unsigned short)0x3F6;
 				} else {
 				} else {
 					b0 = 0x1F0; c0 = 0x3F6;
 					b0 = 0x1F0; c0 = 0x3F6;
 				}
 				}
@@ -92,13 +114,25 @@ void ata_init_ports(void)
 					b1 = (unsigned short)(bar2 & 0xFFFCu);
 					b1 = (unsigned short)(bar2 & 0xFFFCu);
 					c1 = (bar3 & 0x1u)
 					c1 = (bar3 & 0x1u)
 						? (unsigned short)(bar3 & 0xFFFCu)
 						? (unsigned short)(bar3 & 0xFFFCu)
-						: (unsigned short)(b1 + 8);
+						: (unsigned short)0x376;
 				} else {
 				} else {
 					b1 = 0x170; c1 = 0x376;
 					b1 = 0x170; c1 = 0x376;
 				}
 				}
 
 
 				ata_base[0] = b0; ata_ctrl[0] = c0;
 				ata_base[0] = b0; ata_ctrl[0] = c0;
 				ata_base[1] = b1; ata_ctrl[1] = c1;
 				ata_base[1] = b1; ata_ctrl[1] = c1;
+				ata_reset_channel(ata_base[0], ata_ctrl[0]);
+				ata_reset_channel(ata_base[1], ata_ctrl[1]);
+
+				serial_puts(SERIAL_COM1, "ata: ctl ");
+				serial_puthex(SERIAL_COM1, port_inb(c0));
+				serial_putc(SERIAL_COM1, '/');
+				serial_puthex(SERIAL_COM1, port_inb(c0 + 2));
+				serial_putc(SERIAL_COM1, ' ');
+				serial_puthex(SERIAL_COM1, port_inb(c1));
+				serial_putc(SERIAL_COM1, '/');
+				serial_puthex(SERIAL_COM1, port_inb(c1 + 2));
+				serial_putc(SERIAL_COM1, '\n');
 
 
 				serial_puts(SERIAL_COM1, "ata: pci ide ");
 				serial_puts(SERIAL_COM1, "ata: pci ide ");
 				serial_putdec(SERIAL_COM1, bus);
 				serial_putdec(SERIAL_COM1, bus);
@@ -124,25 +158,50 @@ void ata_init_ports(void)
 	serial_puts(SERIAL_COM1, "ata: no PCI IDE function, legacy ports\n");
 	serial_puts(SERIAL_COM1, "ata: no PCI IDE function, legacy ports\n");
 }
 }
 
 
-/* Delay 400 ns by reading the alt-status register a few times. */
-static void ata_400ns(unsigned short ctrl)
+/* Delay 400 ns by reading the command-block status register a few times.
+ * The alt-status port is not used for polling: some IDE functions expose a
+ * BAR that does not answer correctly, and a bogus BSY bit there made every
+ * transfer time out even though the command block reported ready. */
+static void ata_400ns(unsigned short base)
 {
 {
-	(void)port_inb(ctrl);
-	(void)port_inb(ctrl);
-	(void)port_inb(ctrl);
-	(void)port_inb(ctrl);
+	(void)port_inb(base + REG_CMD);
+	(void)port_inb(base + REG_CMD);
+	(void)port_inb(base + REG_CMD);
+	(void)port_inb(base + REG_CMD);
 }
 }
 
 
-static int ata_wait_not_busy(unsigned short ctrl, unsigned int timeout_ms)
+static int ata_wait_not_busy(unsigned short base, unsigned int timeout_ms)
 {
 {
 	unsigned int t0 = get_ticks_ms();
 	unsigned int t0 = get_ticks_ms();
 	while (get_ticks_ms() - t0 < timeout_ms) {
 	while (get_ticks_ms() - t0 < timeout_ms) {
-		if (!(port_inb(ctrl) & SR_BSY))
+		if (!(port_inb(base + REG_CMD) & SR_BSY))
 			return 0;
 			return 0;
 	}
 	}
 	return -1;
 	return -1;
 }
 }
 
 
+/* Assert SRST for ~10 ms.  This aborts a command a crashed/reloaded kernel
+ * left half-transferred (the drive would otherwise stay in DRQ forever and
+ * ignore the next IDENTIFY).  Best effort: a malformed control BAR simply
+ * makes the reset a no-op. */
+static void ata_reset_channel(unsigned short base, unsigned short ctrl)
+{
+	unsigned int t0;
+
+	port_outb(ctrl, 0x04);                    /* SRST */
+	t0 = get_ticks_ms();
+	while (get_ticks_ms() - t0 < 10)
+		;
+	/* nIEN=1: the driver polls, so keep the drive's IRQ line quiet
+	 * instead of leaving a masked level-triggered interrupt asserted. */
+	port_outb(ctrl, 0x02);
+	t0 = get_ticks_ms();
+	while ((port_inb(base + REG_CMD) & SR_BSY) &&
+	       get_ticks_ms() - t0 < 1000)
+		;
+	ata_400ns(base);
+}
+
 static int ata_wait_drq(unsigned short base, unsigned int timeout_ms)
 static int ata_wait_drq(unsigned short base, unsigned int timeout_ms)
 {
 {
 	unsigned int t0 = get_ticks_ms();
 	unsigned int t0 = get_ticks_ms();
@@ -156,14 +215,37 @@ static int ata_wait_drq(unsigned short base, unsigned int timeout_ms)
 	return -1;
 	return -1;
 }
 }
 
 
+/* A command is done only when both BSY and DRQ are clear.  Waiting for BSY
+ * alone can return while the last sector is still pending; the next command
+ * is then ignored and the drive stays in DRQ, which looks like a zeroed /
+ * unmountable filesystem. */
+static int ata_wait_idle(unsigned short base, unsigned int timeout_ms)
+{
+	unsigned int t0 = get_ticks_ms();
+
+	while (get_ticks_ms() - t0 < timeout_ms) {
+		unsigned char st = port_inb(base + REG_CMD);
+
+		if (st & SR_ERR)
+			return -1;
+		if (!(st & (SR_BSY | SR_DRQ)))
+			return 0;
+	}
+	return -1;
+}
+
 static int ata_identify(int bus, int unit, unsigned short *id)
 static int ata_identify(int bus, int unit, unsigned short *id)
 {
 {
 	unsigned short base = ata_base[bus];
 	unsigned short base = ata_base[bus];
-	unsigned short ctrl = ata_ctrl[bus];
 	unsigned char st;
 	unsigned char st;
 	unsigned int t0;
 	unsigned int t0;
 	unsigned int i;
 	unsigned int i;
 
 
+	/* A previous failed transfer can leave the drive waiting for PIO
+	 * data, in which case it ignores IDENTIFY and returns zeros. */
+	if (ata_wait_idle(base, 1000) != 0)
+		ata_reset_channel(base, ata_ctrl[bus]);
+
 	port_outb(base + REG_DRIVE, (unsigned char)(0xA0 | (unit << 4)));
 	port_outb(base + REG_DRIVE, (unsigned char)(0xA0 | (unit << 4)));
 	port_outb(base + REG_COUNT, 0);
 	port_outb(base + REG_COUNT, 0);
 	port_outb(base + REG_LBA_LO, 0);
 	port_outb(base + REG_LBA_LO, 0);
@@ -171,7 +253,7 @@ static int ata_identify(int bus, int unit, unsigned short *id)
 	port_outb(base + REG_LBA_HI, 0);
 	port_outb(base + REG_LBA_HI, 0);
 	port_outb(base + REG_CMD, CMD_IDENTIFY);
 	port_outb(base + REG_CMD, CMD_IDENTIFY);
 
 
-	ata_400ns(ctrl);
+	ata_400ns(base);
 
 
 	t0 = get_ticks_ms();
 	t0 = get_ticks_ms();
 	for (;;) {
 	for (;;) {
@@ -180,7 +262,7 @@ static int ata_identify(int bus, int unit, unsigned short *id)
 			return -1;
 			return -1;
 		if (!(st & SR_BSY))
 		if (!(st & SR_BSY))
 			break;
 			break;
-		if (get_ticks_ms() - t0 > 4000)
+		if (get_ticks_ms() - t0 > ATA_TIMEOUT_MS)
 			return -1;
 			return -1;
 	}
 	}
 	if (!(st & SR_DRQ))
 	if (!(st & SR_DRQ))
@@ -228,87 +310,178 @@ int ata_identify_parse(const unsigned short *id, unsigned int *total_sectors, ch
 int ata_probe(int bus, int unit, unsigned int *total_sectors, char model[41])
 int ata_probe(int bus, int unit, unsigned int *total_sectors, char model[41])
 {
 {
 	static unsigned short id[256];
 	static unsigned short id[256];
+	int r;
 
 
 	if (ata_identify(bus, unit, id) != 0)
 	if (ata_identify(bus, unit, id) != 0)
 		return -1;
 		return -1;
 
 
-	return ata_identify_parse(id, total_sectors, model);
+	r = ata_identify_parse(id, total_sectors, model);
+	if (r == 0)
+		ata_lba48[bus] = (id[83] & 0x0400) != 0;
+	return r;
 }
 }
 
 
-static inline void ata_insw(unsigned short port, void *dst, unsigned int count)
+static void ata_log_failure(int write, unsigned int lba, unsigned int count,
+			    const char *what, unsigned short base)
 {
 {
-	__asm__ volatile ("rep insw"
-		: "+D"(dst), "+c"(count)
-		: "d"(port)
-		: "memory");
+	unsigned char st = port_inb(base + REG_CMD);
+	unsigned char err = port_inb(base + REG_ERROR);
+
+	serial_puts(SERIAL_COM1, "ata: ");
+	serial_puts(SERIAL_COM1, write ? "write" : "read");
+	serial_puts(SERIAL_COM1, " failed (");
+	serial_puts(SERIAL_COM1, what);
+	serial_puts(SERIAL_COM1, ") lba ");
+	serial_putdec(SERIAL_COM1, lba);
+	serial_puts(SERIAL_COM1, " count ");
+	serial_putdec(SERIAL_COM1, count);
+	serial_puts(SERIAL_COM1, " status ");
+	serial_puthex(SERIAL_COM1, st);
+	serial_puts(SERIAL_COM1, " error ");
+	serial_puthex(SERIAL_COM1, err);
+	serial_puts(SERIAL_COM1, " cnt ");
+	serial_puthex(SERIAL_COM1, port_inb(base + REG_COUNT));
+	serial_puts(SERIAL_COM1, " lba ");
+	serial_puthex(SERIAL_COM1,
+		      port_inb(base + REG_LBA_LO) |
+		      (port_inb(base + REG_LBA_MID) << 8) |
+		      (port_inb(base + REG_LBA_HI) << 16));
+	serial_putc(SERIAL_COM1, '\n');
 }
 }
 
 
-static inline void ata_outsw(unsigned short port, const void *src, unsigned int count)
+/* Use explicit 16-bit port reads/writes instead of `rep ins/outs`.  The
+ * string form writes through ES:EDI; the C loop uses the normal data
+ * segment and is the same path IDENTIFY already uses successfully on the
+ * real MCP79 board.  A sector is only 256 words, so the speed difference
+ * is small compared with the drive's PIO timing. */
+static void ata_insw(unsigned short port, void *dst, unsigned int count)
 {
 {
-	__asm__ volatile ("rep outsw"
-		: "+S"(src), "+c"(count)
-		: "d"(port)
-		: "memory");
+	unsigned short *p = (unsigned short *)dst;
+
+	while (count--)
+		*p++ = port_inw(port);
+}
+
+static void ata_outsw(unsigned short port, const void *src, unsigned int count)
+{
+	const unsigned short *p = (const unsigned short *)src;
+
+	while (count--)
+		port_outw(port, *p++);
 }
 }
 
 
 static int ata_xfer(int bus, int unit, unsigned int lba, void *buf,
 static int ata_xfer(int bus, int unit, unsigned int lba, void *buf,
 		    unsigned int count, int write)
 		    unsigned int count, int write)
 {
 {
 	unsigned short base = ata_base[bus];
 	unsigned short base = ata_base[bus];
-	unsigned short ctrl = ata_ctrl[bus];
 	unsigned char *p = buf;
 	unsigned char *p = buf;
-	unsigned int done = 0;
+	unsigned int done = 0, i;
+
+	if (ata_wait_idle(base, 1000) != 0)
+		ata_reset_channel(base, ata_ctrl[bus]);
 
 
 	while (done < count) {
 	while (done < count) {
 		unsigned int chunk = count - done;
 		unsigned int chunk = count - done;
 		int lba48;
 		int lba48;
 		unsigned int cur = lba + done;
 		unsigned int cur = lba + done;
 
 
-		if (chunk > 255)
+		if (ata_single[bus])
+			chunk = 1;
+		else if (chunk > 255)
 			chunk = 255;
 			chunk = 255;
-		lba48 = ((cur + chunk - 1) >= 0x10000000u);
-
-		if (lba48) {
-			port_outb(base + REG_DRIVE, (unsigned char)(0x40 | (unit << 4)));
-			port_outb(base + REG_COUNT, (unsigned char)(chunk >> 8));
-			port_outb(base + REG_LBA_LO, (unsigned char)(cur >> 24));
-			port_outb(base + REG_LBA_MID, 0);
-			port_outb(base + REG_LBA_HI, 0);
-			port_outb(base + REG_COUNT, (unsigned char)(chunk & 0xFF));
-			port_outb(base + REG_LBA_LO, (unsigned char)(cur & 0xFF));
-			port_outb(base + REG_LBA_MID, (unsigned char)((cur >> 8) & 0xFF));
-			port_outb(base + REG_LBA_HI, (unsigned char)((cur >> 16) & 0xFF));
-			port_outb(base + REG_CMD, (unsigned char)(write ? CMD_WRITE_EXT : CMD_READ_EXT));
-		} else {
-			port_outb(base + REG_DRIVE,
-				  (unsigned char)(0xE0 | (unit << 4) | ((cur >> 24) & 0x0F)));
-			port_outb(base + REG_COUNT, (unsigned char)(chunk & 0xFF));
-			port_outb(base + REG_LBA_LO, (unsigned char)(cur & 0xFF));
-			port_outb(base + REG_LBA_MID, (unsigned char)((cur >> 8) & 0xFF));
-			port_outb(base + REG_LBA_HI, (unsigned char)((cur >> 16) & 0xFF));
-			port_outb(base + REG_CMD, (unsigned char)(write ? CMD_WRITE : CMD_READ));
+		lba48 = ata_lba48[bus] ||
+			((cur + chunk - 1) >= 0x10000000u);
+
+		{
+			unsigned char cmd;
+
+			if (lba48) {
+				port_outb(base + REG_DRIVE, (unsigned char)(0x40 | (unit << 4)));
+				port_outb(base + REG_COUNT, (unsigned char)(chunk >> 8));
+				port_outb(base + REG_LBA_LO, (unsigned char)(cur >> 24));
+				port_outb(base + REG_LBA_MID, 0);
+				port_outb(base + REG_LBA_HI, 0);
+				port_outb(base + REG_COUNT, (unsigned char)(chunk & 0xFF));
+				port_outb(base + REG_LBA_LO, (unsigned char)(cur & 0xFF));
+				port_outb(base + REG_LBA_MID, (unsigned char)((cur >> 8) & 0xFF));
+				port_outb(base + REG_LBA_HI, (unsigned char)((cur >> 16) & 0xFF));
+				cmd = (unsigned char)(write ? CMD_WRITE_EXT : CMD_READ_EXT);
+			} else {
+				port_outb(base + REG_DRIVE,
+					  (unsigned char)(0xE0 | (unit << 4) | ((cur >> 24) & 0x0F)));
+				port_outb(base + REG_COUNT, (unsigned char)(chunk & 0xFF));
+				port_outb(base + REG_LBA_LO, (unsigned char)(cur & 0xFF));
+				port_outb(base + REG_LBA_MID, (unsigned char)((cur >> 8) & 0xFF));
+				port_outb(base + REG_LBA_HI, (unsigned char)((cur >> 16) & 0xFF));
+				cmd = (unsigned char)(write ? CMD_WRITE : CMD_READ);
+			}
+
+			if (!ata_tf_logged) {
+				ata_tf_logged = 1;
+				serial_puts(SERIAL_COM1, "ata: tf cnt ");
+				serial_puthex(SERIAL_COM1, port_inb(base + REG_COUNT));
+				serial_puts(SERIAL_COM1, " lba ");
+				serial_puthex(SERIAL_COM1,
+					      port_inb(base + REG_LBA_LO) |
+					      (port_inb(base + REG_LBA_MID) << 8) |
+					      (port_inb(base + REG_LBA_HI) << 16));
+				serial_puts(SERIAL_COM1, " drv ");
+				serial_puthex(SERIAL_COM1, port_inb(base + REG_DRIVE));
+				serial_puts(SERIAL_COM1, " cmd ");
+				serial_puthex(SERIAL_COM1, cmd);
+				serial_putc(SERIAL_COM1, '\n');
+			}
+			port_outb(base + REG_CMD, cmd);
 		}
 		}
 
 
-		ata_400ns(ctrl);
-		if (ata_wait_not_busy(ctrl, 4000) != 0)
-			return -1;
-		if (ata_wait_drq(base, 4000) != 0)
-			return -1;
+		ata_400ns(base);
+
+		/* PIO transfers must wait for DRQ before *each* sector: the
+		 * drive drops DRQ between sectors while it commits the previous
+		 * one, and writing into the data register while DRQ is low is
+		 * silently lost.  A single rep outsw over a large chunk looked
+		 * fine for one sector but left the drive waiting for more data
+		 * (DRQ set, count/LBA registers advanced), so the next command
+		 * read stale data and a large format eventually failed. */
+		for (i = 0; i < chunk; i++) {
+			if (ata_wait_not_busy(base, ATA_TIMEOUT_MS) != 0) {
+				ata_log_failure(write, cur + i, 1,
+						"busy timeout", base);
+				goto xfer_fail;
+			}
+			if (ata_wait_drq(base, ATA_TIMEOUT_MS) != 0) {
+				ata_log_failure(write, cur + i, 1,
+						"drq timeout", base);
+				goto xfer_fail;
+			}
+			if (write)
+				ata_outsw(base + REG_DATA, p + i * 512, 256);
+			else
+				ata_insw(base + REG_DATA, p + i * 512, 256);
+		}
 
 
-		if (write) {
-			ata_outsw(base + REG_DATA, p, chunk * 256);
-			/* Wait for the drive to finish writing to media (BSY clears
-			 * after the data transfer) before issuing the next command. */
-			if (ata_wait_not_busy(ctrl, 4000) != 0)
-				return -1;
-			if (port_inb(base + REG_CMD) & SR_ERR)
-				return -1;
-		} else {
-			ata_insw(base + REG_DATA, p, chunk * 256);
+		/* Let the last sector finish before the next command. */
+		if (ata_wait_idle(base, ATA_COMPLETE_TIMEOUT_MS) != 0) {
+			ata_log_failure(write, cur, chunk, "completion timeout", base);
+			goto xfer_fail;
+		}
+		if (port_inb(base + REG_CMD) & SR_ERR) {
+			ata_log_failure(write, cur, chunk, "transfer error", base);
+			goto xfer_fail;
 		}
 		}
 
 
 		p += chunk * 512;
 		p += chunk * 512;
 		done += chunk;
 		done += chunk;
+		continue;
+
+xfer_fail:
+		ata_reset_channel(base, ata_ctrl[bus]);
+		if (ata_single[bus])
+			return -1;
+		/* A multi-sector command upset this bridge; retry from the same
+		 * sector with one ATA command per sector. */
+		ata_single[bus] = 1;
+		serial_puts(SERIAL_COM1, "ata: switching to single-sector PIO\n");
 	}
 	}
 	return 0;
 	return 0;
 }
 }
@@ -322,3 +495,28 @@ int ata_write_sectors(int bus, int unit, unsigned int lba, const void *buf, unsi
 {
 {
 	return ata_xfer(bus, unit, lba, (void *)buf, count, 1);
 	return ata_xfer(bus, unit, lba, (void *)buf, count, 1);
 }
 }
+
+int ata_flush(int bus, int unit)
+{
+	unsigned short base;
+
+	if (bus < 0 || bus > 1)
+		return -1;
+	base = ata_base[bus];
+	if (ata_wait_idle(base, 1000) != 0)
+		ata_reset_channel(base, ata_ctrl[bus]);
+	port_outb(base + REG_DRIVE, (unsigned char)(0xA0 | (unit << 4)));
+	port_outb(base + REG_CMD, 0xE7);          /* FLUSH CACHE */
+	ata_400ns(base);
+	if (ata_wait_idle(base, ATA_TIMEOUT_MS) != 0) {
+		ata_log_failure(1, 0, 0, "cache flush timeout", base);
+		ata_reset_channel(base, ata_ctrl[bus]);
+		return -1;
+	}
+	if (port_inb(base + REG_CMD) & SR_ERR) {
+		ata_log_failure(1, 0, 0, "cache flush error", base);
+		ata_reset_channel(base, ata_ctrl[bus]);
+		return -1;
+	}
+	return 0;
+}

+ 4 - 0
ata.h

@@ -21,4 +21,8 @@ int ata_identify_parse(const unsigned short *id, unsigned int *total_sectors, ch
 int ata_read_sectors(int bus, int unit, unsigned int lba, void *buf, unsigned int count);
 int ata_read_sectors(int bus, int unit, unsigned int lba, void *buf, unsigned int count);
 int ata_write_sectors(int bus, int unit, unsigned int lba, const void *buf, unsigned int count);
 int ata_write_sectors(int bus, int unit, unsigned int lba, const void *buf, unsigned int count);
 
 
+/* Flush the drive's write cache (FLUSH CACHE).  Formatting calls this before
+ * it remounts the fresh filesystem. */
+int ata_flush(int bus, int unit);
+
 #endif
 #endif

+ 11 - 0
blkdev.c

@@ -140,3 +140,14 @@ int blk_write(blk_dev_t *d, unsigned int lba, const void *buf, unsigned int coun
 		return ahci_write_sectors(d->unit, lba, buf, count);
 		return ahci_write_sectors(d->unit, lba, buf, count);
 	return ata_write_sectors(d->bus, d->unit, lba, buf, count);
 	return ata_write_sectors(d->bus, d->unit, lba, buf, count);
 }
 }
+
+int blk_flush(blk_dev_t *d)
+{
+	if (!d)
+		return -1;
+	if (d->kind == BLK_FLOPPY)
+		return 0;
+	if (d->kind == BLK_SATA)
+		return ahci_flush(d->unit);
+	return ata_flush(d->bus, d->unit);
+}

+ 3 - 0
blkdev.h

@@ -30,4 +30,7 @@ blk_dev_t *blk_find(const char *name);
 int blk_read(blk_dev_t *d, unsigned int lba, void *buf, unsigned int count);
 int blk_read(blk_dev_t *d, unsigned int lba, void *buf, unsigned int count);
 int blk_write(blk_dev_t *d, unsigned int lba, const void *buf, unsigned int count);
 int blk_write(blk_dev_t *d, unsigned int lba, const void *buf, unsigned int count);
 
 
+/* Flush the device's write cache.  Floppies have none and return 0. */
+int blk_flush(blk_dev_t *d);
+
 #endif
 #endif

+ 126 - 27
fatformat.c

@@ -17,18 +17,33 @@ volatile int format_busy;
 volatile unsigned int format_owner_pid;
 volatile unsigned int format_owner_pid;
 
 
 static unsigned int fmt_total, fmt_done, fmt_last_pct;
 static unsigned int fmt_total, fmt_done, fmt_last_pct;
+static const char *fmt_stage = "?";
+static int fmt_error_printed;
+
+/* Format output goes through the tty, which the netlog mirror captures. */
+static void format_puts(const char *s)
+{
+	io_putstr(s);
+}
+
+void format_putdec(unsigned int v)
+{
+	char b[11];
+	unsigned int n = sizeof(b) - 1;
+
+	b[n] = '\0';
+	do {
+		b[--n] = (char)('0' + v % 10);
+		v /= 10;
+	} while (v);
+	io_putstr(&b[n]);
+}
 
 
 static void format_pct(unsigned int pct)
 static void format_pct(unsigned int pct)
 {
 {
-	char b[4];
-	unsigned int n = 0;
-
-	b[n++] = (char)('0' + pct / 100);
-	b[n++] = (char)('0' + (pct / 10) % 10);
-	b[n++] = (char)('0' + pct % 10);
-	io_putstr("format: ");
-	{ unsigned int i; for (i = 0; i < n; i++) io_putchar(b[i]); }
-	io_putstr("%\n");
+	format_puts("format: ");
+	format_putdec(pct);
+	format_puts("%\n");
 }
 }
 
 
 static void format_progress(unsigned int sectors)
 static void format_progress(unsigned int sectors)
@@ -56,6 +71,16 @@ static int format_write(blk_dev_t *d, unsigned int lba, const void *buf,
 	bkl_pause();
 	bkl_pause();
 	r = blk_write(d, lba, buf, count);
 	r = blk_write(d, lba, buf, count);
 	bkl_resume();
 	bkl_resume();
+	if (r != 0 && !fmt_error_printed) {
+		fmt_error_printed = 1;
+		format_puts("format: write failed at stage ");
+		format_puts(fmt_stage);
+		format_puts(": lba ");
+		format_putdec(lba);
+		format_puts(" count ");
+		format_putdec(count);
+		format_puts(" sectors\n");
+	}
 	return r;
 	return r;
 }
 }
 
 
@@ -214,7 +239,7 @@ static void build_fsinfo_sector(unsigned char *s)
 	put32(s + 0x1FC, 0xAA550000u);   /* TrailSig */
 	put32(s + 0x1FC, 0xAA550000u);   /* TrailSig */
 }
 }
 
 
-int fat_format(blk_dev_t *d)
+int fat_format_limited(blk_dev_t *d, unsigned int limit_sectors)
 {
 {
 	static unsigned char sec[SEC_SIZE];
 	static unsigned char sec[SEC_SIZE];
 	static unsigned char fat_sec[SEC_SIZE];
 	static unsigned char fat_sec[SEC_SIZE];
@@ -226,21 +251,54 @@ int fat_format(blk_dev_t *d)
 	unsigned int reserved, num_fats = 2, sec_per_fat, root_dir_sectors;
 	unsigned int reserved, num_fats = 2, sec_per_fat, root_dir_sectors;
 	unsigned int clusters, fat_start, root_start, data_start;
 	unsigned int clusters, fat_start, root_start, data_start;
 	unsigned int media;
 	unsigned int media;
-	int is_floppy = (d->kind == BLK_FLOPPY);
+	int is_floppy;
 	unsigned int i;
 	unsigned int i;
+	int rc = -1;
+
+	fmt_stage = "layout";
+	fmt_error_printed = 0;
 
 
-	if (!d)
+	if (!d) {
+		format_puts("format: no device\n");
 		return -1;
 		return -1;
+	}
+	is_floppy = (d->kind == BLK_FLOPPY);
 
 
 	if (is_floppy) {
 	if (is_floppy) {
+		if (limit_sectors) {
+			format_puts("format: a floppy is always the full 1440 KiB\n");
+			return -1;
+		}
 		fs_sectors = 2880;
 		fs_sectors = 2880;
 		part_start = 0;
 		part_start = 0;
 		media = 0xF0;
 		media = 0xF0;
 	} else {
 	} else {
-		if (d->total_sectors < (2048 + 64))
-			return -1;   /* too small to partition */
+		unsigned int avail;
+
+		if (d->total_sectors < (2048 + 64)) {
+			format_puts("format: disk too small (");
+			format_putdec(d->total_sectors);
+			format_puts(" sectors)\n");
+			return -1;
+		}
 		part_start = 2048;
 		part_start = 2048;
-		fs_sectors = d->total_sectors - part_start;
+		avail = d->total_sectors - part_start;
+		fs_sectors = avail;
+		if (limit_sectors) {
+			if (limit_sectors > avail) {
+				format_puts("format: size exceeds device (");
+				format_putdec(avail / 2048);
+				format_puts(" MiB available)\n");
+				return -1;
+			}
+			fs_sectors = limit_sectors;
+		}
+		if (fs_sectors < 64) {
+			format_puts("format: partition too small (");
+			format_putdec(fs_sectors);
+			format_puts(" sectors)\n");
+			return -1;
+		}
 		media = 0xF8;
 		media = 0xF8;
 	}
 	}
 
 
@@ -268,6 +326,32 @@ int fat_format(blk_dev_t *d)
 	fmt_done = 0;
 	fmt_done = 0;
 	fmt_last_pct = 0;
 	fmt_last_pct = 0;
 
 
+	format_puts("format: ");
+	format_puts(d->name);
+	format_puts(": ");
+	format_putdec(d->total_sectors);
+	format_puts(" sectors");
+	if (is_floppy) {
+		format_puts(" (1440 KiB)");
+	} else if (d->total_sectors >= 2048) {
+		format_puts(" (");
+		format_putdec(d->total_sectors / 2048);
+		format_puts(" MiB)");
+	}
+	format_puts(", FAT");
+	format_putdec(type);
+	format_puts(", partition ");
+	format_putdec(part_start);
+	format_puts("+");
+	format_putdec(fs_sectors);
+	format_puts(", cluster ");
+	format_putdec(spc);
+	format_puts(", ");
+	format_putdec(num_fats);
+	format_puts(" x ");
+	format_putdec(sec_per_fat);
+	format_puts(" FAT sectors\n");
+
 	zero_sector(zero);
 	zero_sector(zero);
 
 
 	/* Bulk zero buffer (a 1 TB FAT32 has ~2 M FAT sectors; single-sector
 	/* Bulk zero buffer (a 1 TB FAT32 has ~2 M FAT sectors; single-sector
@@ -293,6 +377,7 @@ int fat_format(blk_dev_t *d)
 	/* 1. MBR (IDE/SATA only). */
 	/* 1. MBR (IDE/SATA only). */
 	if (!is_floppy) {
 	if (!is_floppy) {
 		unsigned char *e;
 		unsigned char *e;
+		fmt_stage = "mbr";
 		zero_sector(sec);
 		zero_sector(sec);
 		e = sec + 0x1BE;
 		e = sec + 0x1BE;
 		e[0] = 0x80;                            /* bootable */
 		e[0] = 0x80;                            /* bootable */
@@ -304,22 +389,26 @@ int fat_format(blk_dev_t *d)
 		sec[510] = 0x55;
 		sec[510] = 0x55;
 		sec[511] = 0xAA;
 		sec[511] = 0xAA;
 		if (format_write(d, 0, sec, 1) != 0)
 		if (format_write(d, 0, sec, 1) != 0)
-			return -1;
+			goto out;
 	}
 	}
 
 
 	/* 2. Reserved area + boot sector (+ FSInfo/backup for FAT32). */
 	/* 2. Reserved area + boot sector (+ FSInfo/backup for FAT32). */
+	fmt_stage = "reserved";
 	build_boot_sector(sec, type, spc, reserved, num_fats, root_entries,
 	build_boot_sector(sec, type, spc, reserved, num_fats, root_entries,
 			  sec_per_fat, fs_sectors, part_start, media);
 			  sec_per_fat, fs_sectors, part_start, media);
 	if (write_zeros(d, part_start, reserved, zbuf, zchunk) != 0)
 	if (write_zeros(d, part_start, reserved, zbuf, zchunk) != 0)
-		return -1;
+		goto out;
+	fmt_stage = "boot sector";
 	if (format_write(d, part_start, sec, 1) != 0)
 	if (format_write(d, part_start, sec, 1) != 0)
-		return -1;
+		goto out;
 	if (type == 32) {
 	if (type == 32) {
-		if (format_write(d, part_start + 6, sec, 1) != 0)   /* backup boot */
-			return -1;
+		fmt_stage = "backup boot";
+		if (format_write(d, part_start + 6, sec, 1) != 0)
+			goto out;
+		fmt_stage = "fsinfo";
 		build_fsinfo_sector(sec);
 		build_fsinfo_sector(sec);
-		if (format_write(d, part_start + 1, sec, 1) != 0)   /* FSInfo */
-			return -1;
+		if (format_write(d, part_start + 1, sec, 1) != 0)
+			goto out;
 	}
 	}
 
 
 	/* 3. FATs (two copies).  The first sector carries the media byte and
 	/* 3. FATs (two copies).  The first sector carries the media byte and
@@ -327,28 +416,38 @@ int fat_format(blk_dev_t *d)
 	build_fat_first_sector(fat_sec, type, media);
 	build_fat_first_sector(fat_sec, type, media);
 	for (i = 0; i < num_fats; i++) {
 	for (i = 0; i < num_fats; i++) {
 		unsigned int base = part_start + fat_start + i * sec_per_fat;
 		unsigned int base = part_start + fat_start + i * sec_per_fat;
+		fmt_stage = (i == 0) ? "fat 1" : "fat 2";
 		if (format_write(d, base, fat_sec, 1) != 0)
 		if (format_write(d, base, fat_sec, 1) != 0)
-			return -1;
+			goto out;
+		format_progress(1);
 		if (sec_per_fat > 1 &&
 		if (sec_per_fat > 1 &&
 		    write_zeros(d, base + 1, sec_per_fat - 1, zbuf, zchunk) != 0)
 		    write_zeros(d, base + 1, sec_per_fat - 1, zbuf, zchunk) != 0)
-			return -1;
+			goto out;
 	}
 	}
 
 
 	/* 4. Root directory (FAT12/16) or root cluster (FAT32). */
 	/* 4. Root directory (FAT12/16) or root cluster (FAT32). */
+	fmt_stage = "root directory";
 	if (type == 32) {
 	if (type == 32) {
 		if (write_zeros(d, part_start + data_start, spc, zbuf, zchunk) != 0)
 		if (write_zeros(d, part_start + data_start, spc, zbuf, zchunk) != 0)
-			return -1;
+			goto out;
 	} else {
 	} else {
 		if (write_zeros(d, part_start + root_start, root_dir_sectors,
 		if (write_zeros(d, part_start + root_start, root_dir_sectors,
 				zbuf, zchunk) != 0)
 				zbuf, zchunk) != 0)
-			return -1;
+			goto out;
 	}
 	}
 
 
+	rc = 0;
+
+out:
 	if (zpages) {
 	if (zpages) {
 		unsigned int k;
 		unsigned int k;
 		for (k = 0; k < zpages; k++)
 		for (k = 0; k < zpages; k++)
 			mm_free_page((unsigned int)zbuf + k * PAGE_SIZE);
 			mm_free_page((unsigned int)zbuf + k * PAGE_SIZE);
 	}
 	}
+	return rc;
+}
 
 
-	return 0;
+int fat_format(blk_dev_t *d)
+{
+	return fat_format_limited(d, 0);
 }
 }

+ 7 - 1
fatformat.h

@@ -5,8 +5,14 @@
 
 
 #include "blkdev.h"
 #include "blkdev.h"
 
 
-/* Format device d. Returns 0 on success, -1 on error. */
+/* Format device d. Returns 0 on success, -1 on error.  `limit_sectors`
+ * (0 = the whole device) caps the partition size; useful for testing or for
+ * reserving part of a large disk for another filesystem. */
 int fat_format(blk_dev_t *d);
 int fat_format(blk_dev_t *d);
+int fat_format_limited(blk_dev_t *d, unsigned int limit_sectors);
+
+/* Decimal helper for the format messages (terminal + netlog mirror). */
+void format_putdec(unsigned int v);
 
 
 /* Set while a destructive format owns the disks.  Filesystem syscalls wait
 /* Set while a destructive format owns the disks.  Filesystem syscalls wait
  * for it instead of touching a half-written FAT; the owner is exempt. */
  * for it instead of touching a half-written FAT; the owner is exempt. */

+ 152 - 6
format.c

@@ -1,9 +1,11 @@
-/* format command: create a fresh FAT filesystem on a device. Usage: format <device>. */
+/* format command: create a fresh FAT filesystem on a device.
+ * Usage: format <device> [size]   (size: 100mb, 1gb, ...; binary units) */
 
 
 #include "blkdev.h"
 #include "blkdev.h"
 #include "fatformat.h"
 #include "fatformat.h"
 #include "io.h"
 #include "io.h"
 #include "process.h"
 #include "process.h"
+#include "sched.h"
 #include "vga.h"
 #include "vga.h"
 #include "vfs.h"
 #include "vfs.h"
 
 
@@ -18,12 +20,93 @@ static void list_devices(void)
 	io_putchar('\n');
 	io_putchar('\n');
 }
 }
 
 
+/* Parse a size such as 100mb or 1gb into 512-byte sectors.  Units are
+ * binary (1mb = 1024 * 1024 bytes); a bare number means MiB.  Returns 0,
+ * -1 for bad syntax, -2 for too large, -3 for zero. */
+static int parse_size(const char *s, unsigned int *out)
+{
+	unsigned long long v = 0, sectors;
+	unsigned int i = 0, shift = 2;   /* MiB */
+	int c;
+
+	while (s[i] == ' ')
+		i++;
+	if (s[i] < '0' || s[i] > '9')
+		return -1;
+	while (s[i] >= '0' && s[i] <= '9') {
+		if (v > 429496729ULL)
+			return -2;
+		v = v * 10 + (unsigned int)(s[i] - '0');
+		i++;
+	}
+	if (v > 0xFFFFFFFFULL)
+		return -2;
+	while (s[i] == ' ')
+		i++;
+	if (s[i]) {
+		c = s[i];
+		if (c >= 'A' && c <= 'Z')
+			c += 'a' - 'A';
+		if (c == 'k')
+			shift = 1;
+		else if (c == 'm')
+			shift = 2;
+		else if (c == 'g')
+			shift = 3;
+		else if (c == 't')
+			shift = 4;
+		else
+			return -1;
+		i++;
+		c = s[i];
+		if (c >= 'A' && c <= 'Z')
+			c += 'a' - 'A';
+		if (c == 'b')
+			i++;
+	}
+	while (s[i] == ' ')
+		i++;
+	if (s[i])
+		return -1;
+	if (v == 0)
+		return -3;
+	sectors = v << (shift * 10 - 9);
+	if (sectors > 0xFFFFFFFFULL)
+		return -2;
+	*out = (unsigned int)sectors;
+	return 0;
+}
+
+/* Show a sector limit in the friendliest exact unit. */
+static void print_size(unsigned int sectors)
+{
+	if (sectors == 0) {
+		io_putstr("0 sectors");
+	} else if (sectors % 0x80000000u == 0) {   /* 1 TiB */
+		format_putdec(sectors >> 31);
+		io_putstr(" TiB");
+	} else if (sectors % 0x200000u == 0) {     /* 1 GiB */
+		format_putdec(sectors >> 21);
+		io_putstr(" GiB");
+	} else if (sectors % 2048 == 0) {
+		format_putdec(sectors / 2048);
+		io_putstr(" MiB");
+	} else if (sectors % 2 == 0) {
+		format_putdec(sectors / 2);
+		io_putstr(" KiB");
+	} else {
+		format_putdec(sectors);
+		io_putstr(" sectors");
+	}
+}
+
 void program_format_main(const char *arg)
 void program_format_main(const char *arg)
 {
 {
 	blk_dev_t *d;
 	blk_dev_t *d;
 	char name[16];
 	char name[16];
-	unsigned int i = 0, j;
-	int k;
+	const char *p;
+	unsigned int i = 0, j, limit = 0;
+	int k, r;
 
 
 	if (format_busy && process_is_alive(format_owner_pid)) {
 	if (format_busy && process_is_alive(format_owner_pid)) {
 		io_putstr("format: another format is in progress\n");
 		io_putstr("format: another format is in progress\n");
@@ -31,7 +114,7 @@ void program_format_main(const char *arg)
 	}
 	}
 	format_busy = 0;
 	format_busy = 0;
 	if (!arg) {
 	if (!arg) {
-		io_putstr("format: usage format <device>\n");
+		io_putstr("format: usage format <device> [size]\n");
 		list_devices();
 		list_devices();
 		return;
 		return;
 	}
 	}
@@ -44,11 +127,32 @@ void program_format_main(const char *arg)
 	name[j] = '\0';
 	name[j] = '\0';
 
 
 	if (name[0] == '\0') {
 	if (name[0] == '\0') {
-		io_putstr("format: usage format <device>\n");
+		io_putstr("format: usage format <device> [size]\n");
 		list_devices();
 		list_devices();
 		return;
 		return;
 	}
 	}
 
 
+	p = arg + i;
+	while (*p == ' ')
+		p++;
+	if (*p) {
+		r = parse_size(p, &limit);
+		if (r == -1) {
+			io_putstr("format: bad size '");
+			io_putstr(p);
+			io_putstr("' (use e.g. 100mb or 1gb)\n");
+			return;
+		}
+		if (r == -2) {
+			io_putstr("format: size is too large\n");
+			return;
+		}
+		if (r == -3) {
+			io_putstr("format: size must be greater than zero\n");
+			return;
+		}
+	}
+
 	d = blk_find(name);
 	d = blk_find(name);
 	if (!d) {
 	if (!d) {
 		io_putstr("format: unknown device '");
 		io_putstr("format: unknown device '");
@@ -65,8 +169,37 @@ void program_format_main(const char *arg)
 		return;
 		return;
 	}
 	}
 
 
+	if (d->kind == BLK_FLOPPY && limit) {
+		io_putstr("format: a floppy is always the full 1440 KiB\n");
+		return;
+	}
+
+	/* Reject a bad limit before the destructive confirmation prompt. */
+	if (d->kind != BLK_FLOPPY && limit) {
+		unsigned int avail = (d->total_sectors > 2048)
+			? d->total_sectors - 2048 : 0;
+
+		if (limit > avail) {
+			io_putstr("format: ");
+			print_size(limit);
+			io_putstr(" does not fit on ");
+			io_putstr(d->name);
+			io_putstr(" (");
+			print_size(avail);
+			io_putstr(" available)\n");
+			return;
+		}
+	}
+
 	io_putstr("format ");
 	io_putstr("format ");
 	io_putstr(d->name);
 	io_putstr(d->name);
+	if (limit) {
+		io_putstr(" (");
+		print_size(limit);
+		io_putstr(")");
+	} else {
+		io_putstr(" (whole disk)");
+	}
 	io_putstr("? this destroys all data (y/n) ");
 	io_putstr("? this destroys all data (y/n) ");
 	vga_fb_flush();
 	vga_fb_flush();
 
 
@@ -99,11 +232,24 @@ void program_format_main(const char *arg)
 	/* Other filesystem syscalls wait while the FAT is half-written. */
 	/* Other filesystem syscalls wait while the FAT is half-written. */
 	format_owner_pid = current_proc()->pid;
 	format_owner_pid = current_proc()->pid;
 	format_busy = 1;
 	format_busy = 1;
-	if (fat_format(d) != 0) {
+	if (fat_format_limited(d, limit) != 0) {
 		format_busy = 0;
 		format_busy = 0;
 		io_putstr("format: failed\n");
 		io_putstr("format: failed\n");
 		return;
 		return;
 	}
 	}
+	/* Make the drive commit the new metadata before the remount reads it
+	 * back (some IDE/SATA bridges acknowledge PIO writes before the data
+	 * reaches the medium). */
+	{
+		int fr;
+
+		bkl_pause();
+		fr = blk_flush(d);
+		bkl_resume();
+		if (fr != 0)
+			io_putstr("format: cache flush failed; remount may be stale\n");
+	}
+
 	/* Remount only the formatted device; a full vfs_mount_all() would probe
 	/* Remount only the formatted device; a full vfs_mount_all() would probe
 	 * every disk again and was a second large stall. */
 	 * every disk again and was a second large stall. */
 	vfs_remount_device(d);
 	vfs_remount_device(d);

+ 2 - 16
terminal.c

@@ -113,7 +113,7 @@ static const struct kcmd cmds[] = {
 	{ "display",    "display",                       CK_SPAWN, 0, program_display_main, 0, 0, 0 },
 	{ "display",    "display",                       CK_SPAWN, 0, program_display_main, 0, 0, 0 },
 	{ "gfxbench",   "gfxbench",                      CK_SPAWN, 0, program_gfxbench_main, 0, 0, 0 },
 	{ "gfxbench",   "gfxbench",                      CK_SPAWN, 0, program_gfxbench_main, 0, 0, 0 },
 	{ "lsusb",      "lsusb",                         CK_SPAWN, 0, program_lsusb_main, 0, 0, 0 },
 	{ "lsusb",      "lsusb",                         CK_SPAWN, 0, program_lsusb_main, 0, 0, 0 },
-	{ "format",     "format <device>",               CK_CUSTOM, 0, 0, 0, 0, cmd_format },
+	{ "format",     "format <device> [size]",        CK_CUSTOM, 0, 0, 0, 0, cmd_format },
 	{ "lspci",      "lspci [id]",                    CK_SPAWN_ARG, 0, 0, program_lspci_main, 0, 0 },
 	{ "lspci",      "lspci [id]",                    CK_SPAWN_ARG, 0, 0, program_lspci_main, 0, 0 },
 	{ "peek",       "peek <addr> [len]",             CK_SPAWN_ARG, 0, 0, program_peek_main, 0, 0 },
 	{ "peek",       "peek <addr> [len]",             CK_SPAWN_ARG, 0, 0, program_peek_main, 0, 0 },
 	{ "poke",       "poke <addr> <val>",             CK_SPAWN_ARG, CMD_REQARG, 0, program_poke_main, 0, 0 },
 	{ "poke",       "poke <addr> <val>",             CK_SPAWN_ARG, CMD_REQARG, 0, program_poke_main, 0, 0 },
@@ -266,22 +266,8 @@ static int cmd_dbg(struct term *t, const char *args)
 
 
 static int cmd_format(struct term *t, const char *args)
 static int cmd_format(struct term *t, const char *args)
 {
 {
-	char dev[16];
-	unsigned int n = 0;
-	const char *p;
-
 	(void)t;
 	(void)t;
-	while (args[n] && args[n] != ' ' && n + 1 < sizeof(dev))
-		dev[n] = args[n], n++;
-	dev[n] = '\0';
-	p = args + n;
-	while (*p == ' ')
-		p++;
-	if (n == 0 || *p) {
-		io_putstr("format: usage format <device>\n");
-		return 0;
-	}
-	program_format_main(dev);
+	program_format_main(args);
 	return 0;
 	return 0;
 }
 }
 
 

+ 5 - 0
tty.c

@@ -4,6 +4,7 @@
 
 
 #include "tty.h"
 #include "tty.h"
 #include "mm.h"
 #include "mm.h"
+#include "netlog.h"
 #include "process.h"
 #include "process.h"
 
 
 #define TTY_STRIDE (2 * PAGE_SIZE)
 #define TTY_STRIDE (2 * PAGE_SIZE)
@@ -109,6 +110,10 @@ int tty_write(int id, const char *buf, unsigned int len)
 		}
 		}
 		t->buf[t->head] = (unsigned char)buf[i++];
 		t->buf[t->head] = (unsigned char)buf[i++];
 		t->head = next;
 		t->head = next;
+		/* Mirror command output (including ring-3 terminal commands) to
+		 * the network console, like screen_putchar does for the kernel
+		 * terminal. */
+		netlog_char(buf[i - 1]);
 	}
 	}
 	return 0;
 	return 0;
 }
 }

+ 15 - 0
vfs.c

@@ -565,6 +565,16 @@ void vfs_mount_all(void)
 	vfs_mount_ramfs();
 	vfs_mount_ramfs();
 }
 }
 
 
+static int device_is_mounted(const char *dev)
+{
+	unsigned int i;
+
+	for (i = 0; i < vfs_mount_count; i++)
+		if (mount_belongs_to(vfs_mounts[i].name, dev))
+			return 1;
+	return 0;
+}
+
 void vfs_remount_device(blk_dev_t *d)
 void vfs_remount_device(blk_dev_t *d)
 {
 {
 	unsigned char buf[512];
 	unsigned char buf[512];
@@ -573,6 +583,11 @@ void vfs_remount_device(blk_dev_t *d)
 		return;
 		return;
 	unmount_device(d->name);
 	unmount_device(d->name);
 	mount_device(d, buf);
 	mount_device(d, buf);
+	if (!device_is_mounted(d->name)) {
+		io_putstr("vfs: remount of ");
+		io_putstr(d->name);
+		io_putstr(" found no filesystem\n");
+	}
 }
 }
 
 
 vfs_mount_t *vfs_find(const char *name)
 vfs_mount_t *vfs_find(const char *name)