Просмотр исходного кода

Optimize the software desktop compositor

Paint every damage rectangle front-to-back with occlusion culling: keep the
focused window first and subtract each window in front, so covered windows
are never repainted and the stack is no longer drawn back-to-front.

Track per-canvas damage in the window server.  SYS_WIN_PRESENT takes an
optional content-relative rectangle, unions it into canvas_dmg_*, and
SYS_WM_INFO returns the union; the terminal presents only its dirty rows.

Move focused windows by copying their shadow block and repainting only the
old strips the new rectangle does not cover.  Use row-based RGB565 conversion
and rep stos/movs for fills and copies.

Expose the last two-second interval in /share/wmstats and on the netconsole
(frames, total/worst milliseconds and composited pixels) for on-target
measurement.

Verified with the QMP keyboard/cursor tests, multi-window drag/focus
screenshots, and the X201 software presenter (idle 0 ms/frame, about 0.9 ms
for a window drag).
Johannes Zellner 1 неделя назад
Родитель
Сommit
38b09f8195
15 измененных файлов с 663 добавлено и 135 удалено
  1. 29 12
      AGENTS.md
  2. 1 0
      docs/development.html
  3. 32 3
      docs/graphics.html
  4. 9 2
      sys_wm.c
  5. 1 1
      sys_wm.h
  6. 1 1
      syscall.c
  7. 2 1
      syscall.h
  8. 14 1
      ucmd_lib.h
  9. 99 32
      ucmd_term.c
  10. 283 41
      ucmd_wm.c
  11. 110 28
      uwm_lib.c
  12. 3 0
      uwm_lib.h
  13. 68 12
      wm.c
  14. 4 1
      wm.h
  15. 7 0
      wm_abi.h

+ 29 - 12
AGENTS.md

@@ -279,19 +279,33 @@ run area), so adding code no longer moves any address.
   console stays visible until the WM attaches (`wm_server_attach` disables
   it), so a missing `/ramfs/bin/wm` leaves the kernel boot log on screen and
   the supervisor retries.  `wm_server_present` flushes the damage rects;
-  `wm_server_key_wait/poll` provide keys.  `terminal.c` keeps the privileged
-  kernel command registry for the ring-3 terminal (`SYS_SPAWN_KCMD` /
-  `term_kcmd_spawn`), but the kernel terminal entry/shell and the cell-window
-  ABI are gone.
+  `wm_server_key_wait/poll` provide keys.  The WM keeps a front-to-back order
+  (focused first, then descending slot); every damage rectangle is painted
+  by subtracting the windows in front, so an occluded window is never
+  repainted and the stack is not drawn back-to-front.  A focused-window drag
+  copies its shadow block (`usurf_copy`) and repaints only the old strips the
+  new rectangle does not cover.  The kernel hit-test uses the same order.
+  `terminal.c` keeps the privileged kernel command
+  registry for the ring-3 terminal (`SYS_SPAWN_KCMD` / `term_kcmd_spawn`),
+  but the kernel terminal entry/shell and the cell-window ABI are gone.
 - **Window canvas API**: `gfx.c/h` allocates the RGB565 front/back canvases;
   `sys_wm.c` is the ABI bridge.  `SYS_WIN_CREATE` gives a command its window
-  canvas mapped RW at `USER_WIN_BASE` (`0x50000000`); `SYS_WIN_PRESENT` copies
-  the back buffer into the front canvas with interrupts off, so a half-drawn
-  frame can never reach the screen.  `SYS_WIN_INFO`, `SYS_WIN_ACK_RESIZE`,
-  `SYS_WIN_POINTER`, `SYS_WIN_EVENT`, `SYS_WIN_KEY_WAIT` and the generic
-  `SYS_KEY_POLL` handle input.  The WM composites the front canvas; presented
-  frames carry monotonic seq counters, so the WM can never lose one.  Closing
-  a window kills its owner; the reaper frees the canvas.  `clock`, `colors`,
+  canvas mapped RW at `USER_WIN_BASE` (`0x50000000`).  `SYS_WIN_PRESENT`
+  optionally takes a content-relative `struct wm_win_present`; the kernel
+  copies only that rectangle into the front canvas (with interrupts off, so
+  a half-drawn frame can never reach the screen), unions it into
+  `canvas_dmg_*`, and `SYS_WM_INFO` returns the union to the WM.  A present
+  with `w`/`h` zero means the whole canvas.  The terminal tracks dirty rows
+  and presents only those; `uwm_lib.c` uses row-based RGB565 conversion,
+  `rep stos`/`rep movs` fills and copies, and counts composited pixels in
+  `usurf_pixels`.  The WM writes the last two-second interval to
+  `/share/wmstats` (`frames`, `ms`, `max`, `px`) and mirrors the line to the
+  non-blocking netconsole ring (UDP 19290) for on-target measurement.
+  `SYS_WIN_INFO`, `SYS_WIN_ACK_RESIZE`, `SYS_WIN_POINTER`, `SYS_WIN_EVENT`,
+  `SYS_WIN_KEY_WAIT` and the generic `SYS_KEY_POLL` handle input.  The WM
+  composites the front canvas; presented frames carry monotonic seq
+  counters, so the WM can never lose one.  Closing a window kills its owner;
+  the reaper frees the canvas.  `clock`, `colors`,
   `term`, `files` and the other apps are canvas clients.  The old
   `SYS_GFX_BEGIN/PRESENT/END` terminal-takeover service and the kernel
   text-canvas renderer are removed.  Pointer input: `SYS_WIN_POINTER` reports
@@ -906,7 +920,10 @@ narrows it to one host (datagrams carry the broadcast MAC, so the board needs
 no ARP entry for it), `netconsole off`/`on` toggles it, and `netlog <text>`
 sends an ad-hoc line.  Nothing is sent before the NIC is up, the producer
 never blocks (a full buffer drops characters and reports it), and the flush
-pauses while a net command owns the receiver.
+pauses while a net command owns the receiver.  The producer path is
+`netlog_char` (via `screen_putchar`/`serial_putc`) and is non-blocking;
+`SYS_NETLOG` is the direct-send command path — never call it from the WM or
+from any BKL holder, because a blocking NIC TX can wedge the whole board.
 
 ## USB HID (mouse + keyboard) / host controllers
 

+ 1 - 0
docs/development.html

@@ -259,6 +259,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Image library.</strong> <code>make test-images</code> decodes a corpus of PNG/JPEG/GIF/BMP/TGA/PNM/ICO/PAM files and checks blits; the ASan variant catches memory errors.</li>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
 			<li><strong>UEFI.</strong> <code>make test-uefi</code> boots the dual image under OVMF headless and greps the serial log for the boot line.</li>
+			<li><strong>Compositor stats.</strong> The ring-3 WM overwrites <code>/share/wmstats</code> every two seconds with <code>frames</code>, total and worst compositing time in milliseconds, and the pixels drawn in the interval. It also mirrors the line to the non-blocking netconsole ring (UDP 19290), so <code>make netmon</code> shows it on a serial-less board. Read it in a terminal or fetch it over WebDAV to measure a target.</li>
 		</ul>
 	</section>
 

+ 32 - 3
docs/graphics.html

@@ -181,6 +181,33 @@
 			<li><strong>Canvas windows</strong> are generic: the app gets a back buffer, pointer position/buttons/focus and queued press/release edges with capture.</li>
 			<li><strong>Focus and z-order</strong> are explicit; closing a window kills its session and frees its canvas.</li>
 		</ul>
+
+		<h3>Compositing cost</h3>
+		<p>
+			The WM keeps a front-to-back order: the focused window first, then
+			the remaining windows in descending slot order. For each damage
+			rectangle it fills the desktop once and walks that order, subtracting
+			every window in front from the region still uncovered. A window is
+			drawn only in its exposed pieces, so a fully occluded window costs
+			nothing and the stack is never repainted back-to-front. The kernel
+			pointer hit-test uses the same order. A focused-window drag copies
+			its shadow block to the new position and repaints only the old
+			strips the new rectangle does not cover, instead of compositing the
+			window at both positions.
+		</p>
+		<p>
+			<code>SYS_WIN_PRESENT</code> carries a content-relative damage
+			rectangle. The terminal tracks its dirty rows, so a keystroke copies
+			and composites one 8×16 row block instead of the whole 512×512
+			canvas. The kernel unions the rectangles between WM polls and
+			<code>SYS_WM_INFO</code> returns that union; a present with
+			<code>w == 0</code> or <code>h == 0</code> still means the whole
+			canvas. The WM overwrites <code>/share/wmstats</code> every two
+			seconds with the interval's frame count, compositing time, worst
+			frame and pixels drawn (<code>usurf_pixels</code>), which is the
+			on-target compositor measurement; the same line is mirrored to
+			the non-blocking netconsole ring (UDP 19290).
+		</p>
 	</section>
 
 	<section id="canvas">
@@ -189,9 +216,11 @@
 			<code>SYS_WIN_CREATE</code> maps the calling command's window canvas
 			read/write at <code>0x50000000</code>. The process draws RGB565
 			pixels and publishes a finished frame with
-			<code>SYS_WIN_PRESENT</code>. Present copies the back buffer into
-			the composited front canvas with interrupts off, so a half-drawn
-			frame can never reach the screen. Frames carry monotonic sequence
+			<code>SYS_WIN_PRESENT</code>, optionally passing a content-relative
+			rectangle (<code>struct wm_win_present</code>) for the changed
+			region. Present copies that region from the back buffer into the
+			composited front canvas with interrupts off, so a half-drawn frame
+			can never reach the screen. Frames carry monotonic sequence
 			counters, so the WM cannot lose one.
 		</p>
 		<p>

+ 9 - 2
sys_wm.c

@@ -164,9 +164,16 @@ int sys_win_create(const struct win_create *in, struct win_info *out)
 	return r;
 }
 
-int sys_win_present(void)
+int sys_win_present(const struct wm_win_present *in)
 {
-	return wm_server_win_present();
+	struct wm_win_present p;
+
+	if (!in)
+		return wm_server_win_present(0);
+	if (!user_ok(in, sizeof(p), 0))
+		return -1;
+	copy_from_user(&p, in, sizeof(p));
+	return wm_server_win_present(&p);
 }
 
 int sys_win_close(void)

+ 1 - 1
sys_wm.h

@@ -19,7 +19,7 @@ int sys_wm_key_poll(void);
 int sys_wm_sync(void);
 
 int sys_win_create(const struct win_create *in, struct win_info *out);
-int sys_win_present(void);
+int sys_win_present(const struct wm_win_present *in);
 int sys_win_close(void);
 int sys_win_info(struct win_info *out);
 int sys_win_ack_resize(void);

+ 1 - 1
syscall.c

@@ -238,7 +238,7 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		return sys_win_create((const struct win_create *)a1,
 				      (struct win_info *)a2);
 	case SYS_WIN_PRESENT:
-		return sys_win_present();
+		return sys_win_present((const struct wm_win_present *)a1);
 	case SYS_WIN_CLOSE:
 		return sys_win_close();
 	case SYS_WM_RESIZE:

+ 2 - 1
syscall.h

@@ -91,7 +91,8 @@
 #define SYS_WM_SYNC        68  /* () -> 0/-1; run deferred gfx cleanup */
 #define SYS_RTC_DATETIME   69  /* (char *buf, unsigned max) -> 0/-1 */
 #define SYS_WIN_CREATE     70  /* (struct win_create *in, struct win_info *out) */
-#define SYS_WIN_PRESENT    71  /* () -> 0/-1; publish the back canvas */
+#define SYS_WIN_PRESENT    71  /* (const struct wm_win_present *in) -> 0/-1;
+				  NULL or w/h 0 publishes the whole canvas */
 #define SYS_WIN_CLOSE      72  /* () -> 0/-1; close the caller's window */
 #define SYS_WM_RESIZE      83  /* (index, struct wm_size *content) -> 0/-1 */
 #define SYS_WIN_INFO       84  /* (struct win_info *out) -> 0/-1 */

+ 14 - 1
ucmd_lib.h

@@ -267,7 +267,20 @@ static inline int u_win_create(unsigned int w, unsigned int h, const char *title
 
 static inline int u_win_present(void)
 {
-	return u_syscall0(SYS_WIN_PRESENT);
+	return u_syscall1(SYS_WIN_PRESENT, 0);
+}
+
+/* Publish only the content-relative rectangle that changed. */
+static inline int u_win_present_rect(int x, int y, unsigned int w,
+				     unsigned int h)
+{
+	struct wm_win_present in;
+
+	in.x = (unsigned int)x;
+	in.y = (unsigned int)y;
+	in.w = w;
+	in.h = h;
+	return u_syscall1(SYS_WIN_PRESENT, (int)&in);
 }
 
 static inline int u_win_close(void)

+ 99 - 32
ucmd_term.c

@@ -73,12 +73,40 @@ static char hist[HIST_MAX][LINE_MAX];
 static unsigned int hist_count, hist_next;
 static int fg_pid = -1;
 static int dirty = 1;
+static int dirty_full = 1;   /* the whole canvas changed */
+static int dmg_valid;
+static unsigned int dmg_y0, dmg_y1;  /* damage rows, inclusive */
 static int cursor_on = 1;
 static unsigned int last_blink;
 static int sb_drag;
 static int sb_grab_ofs;
 static int wrap_pending;   /* the row is full; the next glyph wraps */
 
+static void mark_full(void)
+{
+	dirty = 1;
+	dirty_full = 1;
+	dmg_valid = 0;
+}
+
+static void mark_row(unsigned int y)
+{
+	if (y >= rows)
+		return;
+	dirty = 1;
+	if (dirty_full)
+		return;
+	if (!dmg_valid) {
+		dmg_y0 = dmg_y1 = y;
+		dmg_valid = 1;
+	} else {
+		if (y < dmg_y0)
+			dmg_y0 = y;
+		if (y > dmg_y1)
+			dmg_y1 = y;
+	}
+}
+
 /* ---- Row log ---- */
 
 static struct trow *row_at(unsigned int i)
@@ -128,6 +156,7 @@ static void append_blank_row(void)
 	int was_full = (row_count >= row_cap);
 
 	row_add_blank();
+	mark_full();   /* the scrollbar thumb may change size */
 	if (was_full) {
 		/* Every logical row moved down one slot; keep the input-line
 		 * anchor pointing at the same row. */
@@ -154,7 +183,7 @@ static void scroll_by(int delta)
 		nv = maxs;
 	if (nv != view) {
 		view = nv;
-		dirty = 1;
+		mark_full();
 	}
 }
 
@@ -170,6 +199,7 @@ static void cell_put(unsigned int x, unsigned int y, char ch)
 	r->cells[x] = (unsigned short)(0x0A00 | (unsigned char)ch);
 	if (x + 1 > r->len)
 		r->len = x + 1;
+	mark_row(y);
 }
 
 static void term_scroll(void)
@@ -180,26 +210,38 @@ static void term_scroll(void)
 
 static void term_newline(void)
 {
+	unsigned int old = cy;
+
 	row_at(origin_row() + cy)->wrapped = 0;
 	wrap_pending = 0;
 	cx = 0;
 	cy++;
-	if (cy >= rows)
+	if (cy >= rows) {
 		term_scroll();
-	dirty = 1;
+		mark_full();
+	} else {
+		mark_row(old);
+		mark_row(cy);
+	}
 }
 
 /* The next glyph does not fit: the row continues on the next one, and the
  * two rows form one logical line that reflow must re-wrap as a unit. */
 static void term_wrap(void)
 {
+	unsigned int old = cy;
+
 	row_at(origin_row() + cy)->wrapped = 1;
 	wrap_pending = 0;
 	cx = 0;
 	cy++;
-	if (cy >= rows)
+	if (cy >= rows) {
 		term_scroll();
-	dirty = 1;
+		mark_full();
+	} else {
+		mark_row(old);
+		mark_row(cy);
+	}
 }
 
 static void term_putc(char c)
@@ -211,7 +253,7 @@ static void term_putc(char c)
 	if (c == '\r') {
 		wrap_pending = 0;
 		cx = 0;
-		dirty = 1;
+		mark_row(cy);
 		return;
 	}
 	if (c == '\b') {
@@ -219,7 +261,6 @@ static void term_putc(char c)
 		if (cx > 0)
 			cx--;
 		cell_put(cx, cy, ' ');
-		dirty = 1;
 		return;
 	}
 	if (c == '\t') {
@@ -237,7 +278,6 @@ static void term_putc(char c)
 	cx++;
 	if (cx >= cols)
 		wrap_pending = 1;   /* stay on this row until the next glyph */
-	dirty = 1;
 }
 
 static void term_puts(const char *s)
@@ -257,7 +297,7 @@ static void term_erase_screen(void)
 		row_blank(row_at(origin_row() + i));
 	cx = cy = 0;
 	wrap_pending = 0;
-	dirty = 1;
+	mark_full();
 }
 
 /* The `clear` builtin: drop the screen and the whole scrollback. */
@@ -270,11 +310,13 @@ static void term_reset(void)
 		row_add_blank();
 	cx = cy = 0;
 	wrap_pending = 0;
-	dirty = 1;
+	mark_full();
 }
 
 static void cursor_set(unsigned int row, unsigned int col)
 {
+	unsigned int old = cy;
+
 	if (row >= rows)
 		row = rows - 1;
 	if (col >= cols)
@@ -282,7 +324,8 @@ static void cursor_set(unsigned int row, unsigned int col)
 	cy = row;
 	cx = col;
 	wrap_pending = 0;
-	dirty = 1;
+	mark_row(old);
+	mark_row(cy);
 }
 
 /* Parse the exact "ESC[row;colH" cursor sequence used by io_set_cursor. */
@@ -356,10 +399,8 @@ static void drain_tty(void)
 	char buf[BUF_MAX];
 	int n;
 
-	while ((n = u_tty_read(tty, buf, sizeof(buf))) > 0) {
+	while ((n = u_tty_read(tty, buf, sizeof(buf))) > 0)
 		tty_feed(buf, (unsigned int)n);
-		dirty = 1;
-	}
 }
 
 /* ---- Scrollbar ---- */
@@ -421,7 +462,7 @@ static void sb_set_from_y(int y)
 	}
 	if (nv != view) {
 		view = nv;
-		dirty = 1;
+		mark_full();
 	}
 }
 
@@ -451,14 +492,14 @@ static void handle_pointer(void)
 		} else if (e.type == WIN_EV_POINTER_UP) {
 			if (sb_drag) {
 				sb_drag = 0;
-				dirty = 1;
+				mark_full();
 			}
 		}
 	}
 	if (sb_drag && u_win_pointer(&p) == 0) {
 		if (!(p.buttons & 1)) {
 			sb_drag = 0;
-			dirty = 1;
+			mark_full();
 		} else {
 			sb_set_from_y(p.y);
 		}
@@ -469,16 +510,28 @@ static void handle_pointer(void)
 
 static void render(void)
 {
-	unsigned int x, y, maxs, start;
+	unsigned int x, y, y0, y1, maxs, start;
 
 	if (!dirty)
 		return;
 	maxs = row_count - rows;
-	if (view > maxs)
+	if (view > maxs) {
 		view = maxs;
+		dirty_full = 1;
+	}
 	start = origin_row() - view;
+	if (dirty_full) {
+		y0 = 0;
+		y1 = rows - 1;
+	} else if (dmg_valid) {
+		y0 = dmg_y0;
+		y1 = dmg_y1;
+	} else {
+		dirty = 0;
+		return;
+	}
 
-	for (y = 0; y < rows; y++) {
+	for (y = y0; y <= y1; y++) {
 		unsigned int idx = start + y;
 		unsigned short *dst = &view_cells[y * cols];
 
@@ -498,18 +551,28 @@ static void render(void)
 		}
 	}
 
-	usurf_fill(&surf, 0, 0, wi.width, wi.height, 0x000000u);
-	usurf_cells(&surf, view_cells, cols, rows, 0, 0, 0, 0,
-		    wi.width, wi.height);
-	if (view == 0 && cursor_on && cy < rows) {
+	if (dirty_full)
+		usurf_fill(&surf, 0, 0, wi.width, wi.height, 0x000000u);
+	else
+		usurf_fill(&surf, 0, (int)(y0 * 16), wi.width,
+			   (y1 - y0 + 1) * 16, 0x000000u);
+	usurf_cells(&surf, &view_cells[y0 * cols], cols, y1 - y0 + 1,
+		    0, (int)(y0 * 16), 0, 0, wi.width, wi.height);
+	if (view == 0 && cursor_on && cy >= y0 && cy <= y1) {
 		unsigned int ccx = (cx < cols) ? cx : (cols ? cols - 1 : 0);
 
 		usurf_fill(&surf, (int)ccx * 8, (int)cy * 16, 2, 16,
 			   0xFFFFFFu);
 	}
 	draw_scrollbar();
-	u_win_present();
+	if (dirty_full)
+		u_win_present();
+	else
+		u_win_present_rect(0, (int)(y0 * 16), wi.width,
+				   (y1 - y0 + 1) * 16);
 	dirty = 0;
+	dirty_full = 0;
+	dmg_valid = 0;
 }
 
 static void line_show(void)
@@ -517,9 +580,10 @@ static void line_show(void)
 	unsigned int i, x, base, k;
 	struct trow *r;
 
+	mark_row(cy);
 	if (view) {
 		view = 0;
-		dirty = 1;
+		mark_full();
 	}
 	base = line_abs;
 	if (base < origin_row())
@@ -533,8 +597,11 @@ static void line_show(void)
 	r->wrapped = 0;
 	/* The input line is the tail of the log: rows after its start are
 	 * leftovers of the previous, possibly longer, version of the line. */
-	for (k = 1; base + k < row_count; k++)
+	for (k = 1; base + k < row_count; k++) {
 		row_blank(row_at(base + k));
+		if (base + k >= origin_row())
+			mark_row(base + k - origin_row());
+	}
 
 	cx = line_col;
 	cy = base - origin_row();
@@ -545,7 +612,7 @@ static void line_show(void)
 		term_putc(line[i]);
 	for (x = cx; x < cols; x++)
 		cell_put(x, cy, ' ');
-	dirty = 1;
+	mark_row(cy);
 }
 
 /* ---- Reflow ---- */
@@ -713,7 +780,7 @@ static void finish_resize(unsigned int new_rows, struct pos_map *cur,
 		lin->abs = row_count - 1;
 	line_abs = lin->abs;
 	line_col = (lin->col < cols) ? lin->col : cols - 1;
-	dirty = 1;
+	mark_full();
 }
 
 static void handle_resize(void)
@@ -788,7 +855,7 @@ static void prompt(void)
 	line_abs = origin_row() + cy;
 	line_col = cx;
 	hist_browse = 0;
-	dirty = 1;
+	mark_row(cy);
 }
 
 static void print_num(unsigned int n)
@@ -1249,7 +1316,7 @@ static void handle_key(int k)
 	if (view) {
 		/* Typing always means the prompt: jump back to the tail. */
 		view = 0;
-		dirty = 1;
+		mark_full();
 	}
 	if (k == 0x03) {
 		if (fg_pid > 0) {
@@ -1402,7 +1469,7 @@ void _start(const char *arg)
 			last_blink = now;
 			cursor_on = !cursor_on;
 			if (view == 0)
-				dirty = 1;
+				mark_row(cy);
 		}
 		render();
 		u_sleep_ms((got || sb_drag) ? 1 : 10);

+ 283 - 41
ucmd_wm.c

@@ -37,6 +37,7 @@ static int bar_temp_c = -1;
 static char bar_msg[24];
 static unsigned int bar_msg_until;
 static int bar_msg_dirty;
+static unsigned int stat_frames, stat_ms, stat_px, stat_max, stat_last;
 
 static void bar_notice(const char *msg)
 {
@@ -239,17 +240,23 @@ static void draw_window_clip(unsigned int idx, int cx, int cy,
 		   cx, cy, cw, ch);
 
 	/* Content: every window presents an RGB565 canvas (the terminal
-	 * renders its cells into one; gfx commands own theirs). */
-	fill_clip((int)content_x, (int)cony, content_w, content_h,
-		  0x000000u, cx, cy, cw, ch);
+	 * renders its cells into one; gfx commands own theirs).  A mapped
+	 * canvas covers the whole content area, so it does not need the black
+	 * underlay. */
 	if (u->mapped && u->map.kind == WM_KIND_GFX) {
 		struct uwm_canvas c;
 
 		c.px = (const unsigned short *)u->map.va;
 		c.w = u->map.w;
 		c.h = u->map.h;
+		if (c.w != content_w || c.h != content_h)
+			fill_clip((int)content_x, (int)cony, content_w, content_h,
+				  0x000000u, cx, cy, cw, ch);
 		usurf_canvas(&screen, &c, (int)content_x, (int)cony,
 			     cx, cy, cw, ch);
+	} else {
+		fill_clip((int)content_x, (int)cony, content_w, content_h,
+			  0x000000u, cx, cy, cw, ch);
 	}
 
 	/* Resize grip (bottom-right corner). */
@@ -267,12 +274,82 @@ static void draw_window_clip(unsigned int idx, int cx, int cy,
 	}
 }
 
-static void draw_rect(int x, int y, unsigned int w, unsigned int h)
+/* Front-to-back window order: the focused window is on top, the others
+ * follow in descending slot order.  Painting and hit-testing share it. */
+static unsigned int build_order(int *order)
+{
+	unsigned int i, n = 0;
+
+	for (i = 0; i < WM_MAX_WINDOWS; i++)
+		if (wins[i].info.used && wins[i].info.focused)
+			order[n++] = (int)i;
+	for (i = WM_MAX_WINDOWS; i-- > 0;)
+		if (wins[i].info.used && !wins[i].info.focused)
+			order[n++] = (int)i;
+	return n;
+}
+
+struct orect {
+	int x, y;
+	unsigned int w, h;
+};
+
+#define OCC_MAX 64
+
+/* r minus cut, split into up to four disjoint rectangles. */
+static unsigned int rect_sub(struct orect *out, const struct orect *r,
+			     const struct orect *cut)
+{
+	int rx0 = r->x, ry0 = r->y;
+	int rx1 = r->x + (int)r->w, ry1 = r->y + (int)r->h;
+	int cx0 = cut->x, cy0 = cut->y;
+	int cx1 = cut->x + (int)cut->w, cy1 = cut->y + (int)cut->h;
+	unsigned int n = 0;
+
+	if (cx0 < rx0) cx0 = rx0;
+	if (cy0 < ry0) cy0 = ry0;
+	if (cx1 > rx1) cx1 = rx1;
+	if (cy1 > ry1) cy1 = ry1;
+	if (cx1 <= cx0 || cy1 <= cy0) {
+		out[0] = *r;
+		return 1;
+	}
+	if (cy0 > ry0) {
+		out[n].x = rx0;
+		out[n].y = ry0;
+		out[n].w = (unsigned int)(rx1 - rx0);
+		out[n].h = (unsigned int)(cy0 - ry0);
+		n++;
+	}
+	if (cy1 < ry1) {
+		out[n].x = rx0;
+		out[n].y = cy1;
+		out[n].w = (unsigned int)(rx1 - rx0);
+		out[n].h = (unsigned int)(ry1 - cy1);
+		n++;
+	}
+	if (cx0 > rx0) {
+		out[n].x = rx0;
+		out[n].y = cy0;
+		out[n].w = (unsigned int)(cx0 - rx0);
+		out[n].h = (unsigned int)(cy1 - cy0);
+		n++;
+	}
+	if (cx1 < rx1) {
+		out[n].x = cx1;
+		out[n].y = cy0;
+		out[n].w = (unsigned int)(rx1 - cx1);
+		out[n].h = (unsigned int)(cy1 - cy0);
+		n++;
+	}
+	return n;
+}
+
+/* Back-to-front repaint, used only if the visible-region list overflows. */
+static void draw_rect_naive(int x, int y, unsigned int w, unsigned int h)
 {
 	unsigned int i;
 
-	if (w == 0 || h == 0 || x >= (int)fbw || y >= (int)fbh)
-		return;
 	usurf_fill(&screen, x, y, w, h, COL_BG);
 	for (i = 0; i < WM_MAX_WINDOWS; i++)
 		if (wins[i].info.used && !wins[i].info.focused &&
@@ -290,26 +367,92 @@ static void draw_rect(int x, int y, unsigned int w, unsigned int h)
 			draw_window_clip(i, x, y, w, h);
 }
 
+static void draw_rect(int x, int y, unsigned int w, unsigned int h)
+{
+	static struct orect cur[OCC_MAX], nxt[OCC_MAX];
+	struct orect dmg;
+	int order[WM_MAX_WINDOWS];
+	unsigned int n, i, j, ncur, nnext;
+	int overflow = 0;
+	int x0 = x, y0 = y, x1 = x + (int)w, y1 = y + (int)h;
+
+	if (w == 0 || h == 0)
+		return;
+	if (x0 < 0) x0 = 0;
+	if (y0 < 0) y0 = 0;
+	if (x1 > (int)fbw) x1 = (int)fbw;
+	if (y1 > (int)fbh) y1 = (int)fbh;
+	if (x1 <= x0 || y1 <= y0)
+		return;
+	dmg.x = x0;
+	dmg.y = y0;
+	dmg.w = (unsigned int)(x1 - x0);
+	dmg.h = (unsigned int)(y1 - y0);
+	usurf_fill(&screen, dmg.x, dmg.y, dmg.w, dmg.h, COL_BG);
+
+	n = build_order(order);
+	for (i = 0; i < n; i++) {
+		struct uwin *u = &wins[order[i]];
+		int wx0 = u->info.x, wy0 = u->info.y;
+		int wx1 = wx0 + (int)u->info.w, wy1 = wy0 + (int)u->info.h;
+
+		if (wx0 < dmg.x) wx0 = dmg.x;
+		if (wy0 < dmg.y) wy0 = dmg.y;
+		if (wx1 > x1) wx1 = x1;
+		if (wy1 > y1) wy1 = y1;
+		if (wx1 <= wx0 || wy1 <= wy0)
+			continue;
+		cur[0].x = wx0;
+		cur[0].y = wy0;
+		cur[0].w = (unsigned int)(wx1 - wx0);
+		cur[0].h = (unsigned int)(wy1 - wy0);
+		ncur = 1;
+		for (j = 0; j < i && ncur; j++) {
+			struct uwin *f = &wins[order[j]];
+			struct orect fr;
+			unsigned int k;
+
+			fr.x = f->info.x;
+			fr.y = f->info.y;
+			fr.w = f->info.w;
+			fr.h = f->info.h;
+			nnext = 0;
+			for (k = 0; k < ncur; k++) {
+				if (nnext + 4 > OCC_MAX) {
+					overflow = 1;
+					break;
+				}
+				nnext += rect_sub(&nxt[nnext], &cur[k], &fr);
+			}
+			if (overflow)
+				break;
+			for (k = 0; k < nnext; k++)
+				cur[k] = nxt[k];
+			ncur = nnext;
+		}
+		if (overflow)
+			break;
+		for (j = 0; j < ncur; j++)
+			draw_window_clip((unsigned int)order[i], cur[j].x,
+					 cur[j].y, cur[j].w, cur[j].h);
+	}
+	if (overflow)
+		draw_rect_naive(dmg.x, dmg.y, dmg.w, dmg.h);
+}
+
 static int window_at(unsigned int mx, unsigned int my)
 {
-	unsigned int i;
+	int order[WM_MAX_WINDOWS];
+	unsigned int n = build_order(order), i;
 
-	for (i = 0; i < WM_MAX_WINDOWS; i++)
-		if (wins[i].info.used && wins[i].info.focused &&
-		    mx >= (unsigned int)wins[i].info.x &&
-		    my >= (unsigned int)wins[i].info.y &&
-		    mx < (unsigned int)(wins[i].info.x + (int)wins[i].info.w) &&
-		    my < (unsigned int)(wins[i].info.y + (int)wins[i].info.h))
-			return (int)i;
-	/* Inactive windows are painted in slot order, so the highest slot is
-	 * the topmost one under the cursor. */
-	for (i = WM_MAX_WINDOWS; i-- > 0; )
-		if (wins[i].info.used && !wins[i].info.focused &&
-		    mx >= (unsigned int)wins[i].info.x &&
-		    my >= (unsigned int)wins[i].info.y &&
-		    mx < (unsigned int)(wins[i].info.x + (int)wins[i].info.w) &&
-		    my < (unsigned int)(wins[i].info.y + (int)wins[i].info.h))
-			return (int)i;
+	for (i = 0; i < n; i++) {
+		struct wm_window_info *w = &wins[order[i]].info;
+
+		if (mx >= (unsigned int)w->x && my >= (unsigned int)w->y &&
+		    mx < (unsigned int)(w->x + (int)w->w) &&
+		    my < (unsigned int)(w->y + (int)w->h))
+			return order[i];
+	}
 	return -1;
 }
 
@@ -355,6 +498,38 @@ static void add_rect(struct wm_present_info *p, int x, int y,
 	}
 }
 
+/* A focused window is topmost, so the shadow contains exactly its pixels in
+ * the old rectangle.  Move that block and repaint only the old part the new
+ * rectangle does not cover. */
+static void move_window_pixels(struct uwin *u, int ox, int oy, int nx, int ny)
+{
+	struct wm_present_info present;
+	struct orect oldr, newr, pieces[4];
+	unsigned int np, k;
+
+	if (u_wm_begin() != 0)
+		return;
+	usurf_copy(&screen, nx, ny, ox, oy, u->info.w, u->info.h);
+	oldr.x = ox;
+	oldr.y = oy;
+	oldr.w = u->info.w;
+	oldr.h = u->info.h;
+	newr.x = nx;
+	newr.y = ny;
+	newr.w = u->info.w;
+	newr.h = u->info.h;
+	np = rect_sub(pieces, &oldr, &newr);
+	for (k = 0; k < np; k++)
+		draw_rect(pieces[k].x, pieces[k].y, pieces[k].w, pieces[k].h);
+	present.count = 0;
+	present.immediate = 1;
+	add_rect(&present, nx, ny, u->info.w, u->info.h);
+	for (k = 0; k < np; k++)
+		add_rect(&present, pieces[k].x, pieces[k].y,
+			 pieces[k].w, pieces[k].h);
+	u_wm_present(&present);
+}
+
 static void do_update(struct wm_status *st)
 {
 	struct wm_present_info present;
@@ -464,13 +639,7 @@ static void do_update(struct wm_status *st)
 		full_redraw = 0;
 		need = 1;
 		{
-			usurf_fill(&screen, 0, 0, fbw, fbh, COL_BG);
-			for (i = 0; i < WM_MAX_WINDOWS; i++)
-				if (wins[i].info.used && !wins[i].info.focused)
-					draw_window_clip(i, 0, 0, fbw, fbh);
-			for (i = 0; i < WM_MAX_WINDOWS; i++)
-				if (wins[i].info.used && wins[i].info.focused)
-					draw_window_clip(i, 0, 0, fbw, fbh);
+			draw_rect(0, 0, fbw, fbh);
 			draw_bar();
 			present.count = 0;
 			add_rect(&present, 0, 0, fbw, fbh);
@@ -699,17 +868,21 @@ static void handle_mouse(struct wm_status *st)
 				u_wm_set_geom((unsigned int)drag_id, nx, ny);
 				u->info.x = nx;
 				u->info.y = ny;
-				present.count = 0;
-				present.immediate = 1;
-				add_rect(&present, ox, oy, u->info.w, u->info.h);
-				add_rect(&present, nx, ny, u->info.w, u->info.h);
-				if (u_wm_begin() == 0) {
-					for (i = 0; i < present.count; i++)
-						draw_rect(present.rect[i].x,
-							  present.rect[i].y,
-							  present.rect[i].w,
-							  present.rect[i].h);
-					u_wm_present(&present);
+				if (u->info.focused) {
+					move_window_pixels(u, ox, oy, nx, ny);
+				} else {
+					present.count = 0;
+					present.immediate = 1;
+					add_rect(&present, ox, oy, u->info.w, u->info.h);
+					add_rect(&present, nx, ny, u->info.w, u->info.h);
+					if (u_wm_begin() == 0) {
+						for (i = 0; i < present.count; i++)
+							draw_rect(present.rect[i].x,
+								  present.rect[i].y,
+								  present.rect[i].w,
+								  present.rect[i].h);
+						u_wm_present(&present);
+					}
 				}
 			}
 		} else {
@@ -722,6 +895,54 @@ static void handle_mouse(struct wm_status *st)
 	prev_buttons = buttons;
 }
 
+static char *put_str(char *p, const char *s)
+{
+	while (*s)
+		*p++ = *s++;
+	return p;
+}
+
+static char *put_dec(char *p, unsigned int v)
+{
+	char b[10];
+	unsigned int n = 0;
+
+	do {
+		b[n++] = (char)('0' + v % 10);
+		v /= 10;
+	} while (v);
+	while (n)
+		*p++ = b[--n];
+	return p;
+}
+
+/* Expose the last interval in /share so the target can be measured without
+ * a serial console. */
+static void write_stats(void)
+{
+	char b[80], *p = b;
+	unsigned int now = u_ticks_ms();
+
+	p = put_str(p, "t=");
+	p = put_dec(p, now / 1000);
+	p = put_str(p, "s frames=");
+	p = put_dec(p, stat_frames);
+	p = put_str(p, " ms=");
+	p = put_dec(p, stat_ms);
+	p = put_str(p, " max=");
+	p = put_dec(p, stat_max);
+	p = put_str(p, " px=");
+	p = put_dec(p, stat_px);
+	p = put_str(p, "\n");
+	u_syscall3(SYS_WRITE_FILE, (int)"/share/wmstats", (int)b,
+		   (int)(p - b));
+	/* Also mirror the line to the non-blocking netconsole ring (UDP 19290)
+	 * so a serial-less board can be measured from the host.  Do not use
+	 * SYS_NETLOG here: a direct NIC send can block while the WM holds the
+	 * BKL and would make the whole board unresponsive. */
+	u_puts(b);
+}
+
 void _start(const char *arg)
 {
 	struct wm_screen_info si;
@@ -741,12 +962,33 @@ void _start(const char *arg)
 	full_redraw = 1;
 
 	for (;;) {
+		unsigned int t0, t1;
+
 		if (u_wm_poll(&st) != 0)
 			u_exit(1);
 		if (st.full_redraw)
 			full_redraw = 1;
+		usurf_pixels = 0;
+		t0 = u_ticks_ms();
 		handle_mouse(&st);
 		do_update(&st);
+		t1 = u_ticks_ms();
+		if (usurf_pixels) {
+			unsigned int dt = t1 - t0;
+
+			stat_frames++;
+			stat_ms += dt;
+			stat_px += usurf_pixels;
+			if (dt > stat_max)
+				stat_max = dt;
+		}
+		if (t1 - stat_last >= 2000) {
+			stat_last = t1;
+			if (stat_frames) {
+				write_stats();
+				stat_frames = stat_ms = stat_px = stat_max = 0;
+			}
+		}
 		u_sleep_ms(10);
 	}
 }

+ 110 - 28
uwm_lib.c

@@ -16,6 +16,8 @@ static const unsigned char pal_b[16] = {
 	0, 0, 170, 0, 170, 170, 0, 170, 85, 255, 85, 255, 85, 255, 85, 255
 };
 
+unsigned int usurf_pixels;
+
 void usurf_init(struct usurf *s, void *px, unsigned int w, unsigned int h,
 		unsigned int pitch, unsigned int bpp)
 {
@@ -33,6 +35,7 @@ static void put_px(struct usurf *s, unsigned int x, unsigned int y,
 
 	if (x >= s->w || y >= s->h)
 		return;
+	usurf_pixels++;
 	p = s->px + (unsigned long)y * s->pitch;
 	if (s->bpp == 16) {
 		unsigned int v = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
@@ -71,29 +74,46 @@ void usurf_fill(struct usurf *s, int x, int y, unsigned int w,
 	if ((unsigned int)y + h > s->h)
 		h = s->h - (unsigned int)y;
 
-	if (s->bpp == 16) {
+	usurf_pixels += w * h;
+	if (s->bpp == 32) {
+		unsigned int v = 0xFF000000u | (r << 16) | (g << 8) | b;
+
+		for (j = 0; j < h; j++) {
+			unsigned int *p = (unsigned int *)(s->px +
+				(unsigned long)((unsigned int)y + j) * s->pitch) +
+				(unsigned int)x;
+			unsigned int n = w;
+
+			__asm__ volatile ("cld; rep stosl"
+					  : "+D"(p), "+c"(n)
+					  : "a"(v)
+					  : "memory");
+		}
+	} else if (s->bpp == 16) {
 		unsigned short v = (unsigned short)(((r >> 3) << 11) |
 					((g >> 2) << 5) | (b >> 3));
+
 		for (j = 0; j < h; j++) {
 			unsigned short *p = (unsigned short *)(s->px +
 				(unsigned long)((unsigned int)y + j) * s->pitch) +
 				(unsigned int)x;
-			for (i = 0; i < w; i++)
-				p[i] = v;
+			unsigned int n = w;
+
+			__asm__ volatile ("cld; rep stosw"
+					  : "+D"(p), "+c"(n)
+					  : "a"(v)
+					  : "memory");
 		}
 	} else {
-		unsigned int pb = s->bpp / 8;
 		for (j = 0; j < h; j++) {
 			unsigned char *p = s->px +
 				(unsigned long)((unsigned int)y + j) * s->pitch +
-				(unsigned int)x * pb;
+				(unsigned int)x * 3;
 			for (i = 0; i < w; i++) {
 				p[0] = (unsigned char)b;
 				p[1] = (unsigned char)g;
 				p[2] = (unsigned char)r;
-				if (pb == 4)
-					p[3] = 0xFF;
-				p += pb;
+				p += 3;
 			}
 		}
 	}
@@ -111,6 +131,7 @@ void usurf_copy(struct usurf *s, int dx, int dy, int sx, int sy,
 	    (unsigned int)dy + h > s->h || (unsigned int)sy + h > s->h)
 		return;
 
+	usurf_pixels += w * h;
 	backwards = (dy > sy) || (dy == sy && dx > sx);
 	{
 		unsigned int i;
@@ -123,15 +144,46 @@ void usurf_copy(struct usurf *s, int dx, int dy, int sx, int sy,
 					     (unsigned int)sx * pb;
 			unsigned char *dst = s->px + (unsigned long)dyy * s->pitch +
 					     (unsigned int)dx * pb;
-			unsigned int n = w * pb;
+			unsigned int n = w;
+
+			if (pb == 4) {
+				unsigned int *d = (unsigned int *)dst;
+				const unsigned int *s32 = (const unsigned int *)src;
 
-			if (backwards) {
-				while (n--)
-					dst[n] = src[n];
+				if (backwards) {
+					while (n--)
+						d[n] = s32[n];
+				} else {
+					__asm__ volatile ("cld; rep movsl"
+							  : "+D"(d), "+c"(n), "+S"(s32)
+							  :
+							  : "memory");
+				}
+			} else if (pb == 2) {
+				unsigned short *d = (unsigned short *)dst;
+				const unsigned short *s16 = (const unsigned short *)src;
+
+				if (backwards) {
+					while (n--)
+						d[n] = s16[n];
+				} else {
+					__asm__ volatile ("cld; rep movsw"
+							  : "+D"(d), "+c"(n), "+S"(s16)
+							  :
+							  : "memory");
+				}
 			} else {
-				unsigned int k;
-				for (k = 0; k < n; k++)
-					dst[k] = src[k];
+				unsigned int k = w * 3;
+
+				if (backwards) {
+					while (k--)
+						dst[k] = src[k];
+				} else {
+					__asm__ volatile ("cld; rep movsb"
+							  : "+D"(dst), "+c"(k), "+S"(src)
+							  :
+							  : "memory");
+				}
 			}
 		}
 	}
@@ -223,7 +275,7 @@ void usurf_canvas(struct usurf *s, const struct uwm_canvas *c,
 		  int x0, int y0,
 		  int cx, int cy, unsigned int cw, unsigned int ch)
 {
-	int x, y;
+	int y;
 	int sx0 = 0, sy0 = 0;
 	int sx1 = (int)c->w, sy1 = (int)c->h;
 
@@ -238,19 +290,49 @@ void usurf_canvas(struct usurf *s, const struct uwm_canvas *c,
 	if (sx1 <= sx0 || sy1 <= sy0)
 		return;
 
+	usurf_pixels += (unsigned int)(sx1 - sx0) * (unsigned int)(sy1 - sy0);
 	for (y = sy0; y < sy1; y++) {
-		for (x = sx0; x < sx1; x++) {
-			unsigned int p = c->px[(unsigned int)y * c->w +
-					       (unsigned int)x];
-			unsigned int r5 = (p >> 11) & 0x1F;
-			unsigned int g6 = (p >> 5) & 0x3F;
-			unsigned int b5 = p & 0x1F;
-			unsigned int r = (r5 << 3) | (r5 >> 2);
-			unsigned int g = (g6 << 2) | (g6 >> 4);
-			unsigned int b = (b5 << 3) | (b5 >> 2);
-
-			put_px(s, (unsigned int)(x0 + x),
-			       (unsigned int)(y0 + y), r, g, b);
+		const unsigned short *src = c->px + (unsigned int)y * c->w +
+					    (unsigned int)sx0;
+		unsigned int yy = (unsigned int)(y0 + y);
+		unsigned int xx = (unsigned int)(x0 + sx0);
+		unsigned char *row = s->px + (unsigned long)yy * s->pitch;
+		unsigned int n = (unsigned int)(sx1 - sx0);
+		unsigned int i;
+
+		if (s->bpp == 32) {
+			unsigned int *d = (unsigned int *)row + xx;
+
+			for (i = 0; i < n; i++) {
+				unsigned int p = src[i];
+				unsigned int r5 = (p >> 11) & 0x1F;
+				unsigned int g6 = (p >> 5) & 0x3F;
+				unsigned int b5 = p & 0x1F;
+
+				d[i] = 0xFF000000u |
+				       (((r5 << 3) | (r5 >> 2)) << 16) |
+				       (((g6 << 2) | (g6 >> 4)) << 8) |
+				       ((b5 << 3) | (b5 >> 2));
+			}
+		} else if (s->bpp == 16) {
+			unsigned short *d = (unsigned short *)row + xx;
+
+			for (i = 0; i < n; i++)
+				d[i] = src[i];
+		} else {
+			unsigned char *d = row + xx * 3;
+
+			for (i = 0; i < n; i++) {
+				unsigned int p = src[i];
+				unsigned int r5 = (p >> 11) & 0x1F;
+				unsigned int g6 = (p >> 5) & 0x3F;
+				unsigned int b5 = p & 0x1F;
+
+				d[0] = (unsigned char)((b5 << 3) | (b5 >> 2));
+				d[1] = (unsigned char)((g6 << 2) | (g6 >> 4));
+				d[2] = (unsigned char)((r5 << 3) | (r5 >> 2));
+				d += 3;
+			}
 		}
 	}
 }

+ 3 - 0
uwm_lib.h

@@ -15,6 +15,9 @@ struct uwm_canvas {
 	unsigned int w, h;
 };
 
+/* Pixels written by the compositor primitives; the WM uses it for stats. */
+extern unsigned int usurf_pixels;
+
 void usurf_init(struct usurf *s, void *px, unsigned int w, unsigned int h,
 		unsigned int pitch, unsigned int bpp);
 void usurf_fill(struct usurf *s, int x, int y, unsigned int w,

+ 68 - 12
wm.c

@@ -170,6 +170,7 @@ static void wm_free_canvas_window(unsigned int idx)
 	}
 	w->pending_pages = 0;
 	w->resize_pending = 0;
+	w->canvas_dmg_w = w->canvas_dmg_h = 0;
 	gfx_free(&w->canvas);
 	w->canvas_window = 0;
 }
@@ -242,6 +243,8 @@ int wm_server_win_create(const struct win_create *in, struct win_info *out)
 	w->pending_back = 0;
 	w->pending_pages = 0;
 	w->resize_pending = 0;
+	w->canvas_dmg_x = w->canvas_dmg_y = 0;
+	w->canvas_dmg_w = w->canvas_dmg_h = 0;
 	w->pw = cw + 2;
 	w->ph = ch + WM_TITLE_H + 2;
 	w->x = 24 + i * 32;
@@ -272,12 +275,12 @@ int wm_server_win_create(const struct win_create *in, struct win_info *out)
 	return 0;
 }
 
-int wm_server_win_present(void)
+int wm_server_win_present(const struct wm_win_present *in)
 {
 	int idx = wm_window_for_pid(current_proc()->pid);
 	struct window *w;
 	const unsigned short *src;
-	unsigned int n, i;
+	unsigned int x = 0, y = 0, rw, rh, row;
 
 	if (idx < 0)
 		return -1;
@@ -285,12 +288,55 @@ int wm_server_win_present(void)
 	if (!w->canvas_window || !w->back || !w->canvas.px ||
 	    w->resize_pending)
 		return -1;
+	rw = w->canvas.w;
+	rh = w->canvas.h;
+	if (in && in->w && in->h) {
+		x = in->x;
+		y = in->y;
+		rw = in->w;
+		rh = in->h;
+		if (x >= w->canvas.w || y >= w->canvas.h)
+			return -1;
+		if (rw > w->canvas.w - x)
+			rw = w->canvas.w - x;
+		if (rh > w->canvas.h - y)
+			rh = w->canvas.h - y;
+	}
+
 	src = (const unsigned short *)USER_WIN_BASE;
-	n = w->canvas.w * w->canvas.h;
-	for (i = 0; i + 1 < n; i += 2)
-		((unsigned int *)w->canvas.px)[i / 2] = ((const unsigned int *)src)[i / 2];
-	if (n & 1)
-		w->canvas.px[n - 1] = src[n - 1];
+	for (row = 0; row < rh; row++) {
+		const unsigned short *s = src + (unsigned long)(y + row) *
+					       w->canvas.w + x;
+		unsigned short *d = w->canvas.px +
+				    (unsigned long)(y + row) * w->canvas.w + x;
+		unsigned int n = rw;
+
+		__asm__ volatile ("cld; rep movsw"
+				  : "+D"(d), "+c"(n), "+S"(s)
+				  :
+				  : "memory");
+	}
+
+	if (!w->canvas_dmg_w || !w->canvas_dmg_h) {
+		w->canvas_dmg_x = x;
+		w->canvas_dmg_y = y;
+		w->canvas_dmg_w = rw;
+		w->canvas_dmg_h = rh;
+	} else {
+		unsigned int x1 = w->canvas_dmg_x + w->canvas_dmg_w;
+		unsigned int y1 = w->canvas_dmg_y + w->canvas_dmg_h;
+
+		if (x < w->canvas_dmg_x)
+			w->canvas_dmg_x = x;
+		if (y < w->canvas_dmg_y)
+			w->canvas_dmg_y = y;
+		if (x + rw > x1)
+			x1 = x + rw;
+		if (y + rh > y1)
+			y1 = y + rh;
+		w->canvas_dmg_w = x1 - w->canvas_dmg_x;
+		w->canvas_dmg_h = y1 - w->canvas_dmg_y;
+	}
 	w->canvas.seq++;
 	return 0;
 }
@@ -376,6 +422,7 @@ int wm_server_win_ack_resize(void)
 	w->pending_back = 0;
 	w->pending_pages = 0;
 	w->resize_pending = 0;
+	w->canvas_dmg_w = w->canvas_dmg_h = 0;
 	return 0;
 }
 
@@ -454,6 +501,8 @@ int wm_server_resize(unsigned int index, unsigned int cw, unsigned int ch)
 	w->canvas = nf;
 	w->canvas.seq = 1;
 	w->canvas.drawn = 0;
+	w->canvas_dmg_x = w->canvas_dmg_y = 0;
+	w->canvas_dmg_w = w->canvas_dmg_h = 0;
 	w->pending_back = nb;
 	w->pending_pages = pages;
 	w->resize_pending = 1;
@@ -607,10 +656,15 @@ int wm_server_info(unsigned int index, struct wm_window_info *out)
 	out->content_h = g->h;
 	out->dirty = (g->seq != g->drawn);
 	out->dirty_seq = g->seq;
-	out->dmg_x = 0;
-	out->dmg_y = 0;
-	out->dmg_w = g->w;
-	out->dmg_h = g->h;
+	if (out->dirty && w->canvas_dmg_w && w->canvas_dmg_h) {
+		out->dmg_x = w->canvas_dmg_x;
+		out->dmg_y = w->canvas_dmg_y;
+		out->dmg_w = w->canvas_dmg_w;
+		out->dmg_h = w->canvas_dmg_h;
+	} else if (out->dirty) {
+		out->dmg_w = g->w;
+		out->dmg_h = g->h;
+	}
 	return 1;
 }
 
@@ -681,8 +735,10 @@ int wm_server_ack(unsigned int index, unsigned int seq)
 	w = &windows[index];
 	if (!w->used || !w->canvas_window)
 		return -1;
-	if (seq == w->canvas.seq)
+	if (seq == w->canvas.seq) {
 		w->canvas.drawn = seq;
+		w->canvas_dmg_w = w->canvas_dmg_h = 0;
+	}
 	return 0;
 }
 

+ 4 - 1
wm.h

@@ -30,6 +30,9 @@ struct window {
 	/* Pointer press/release edges for a generic canvas window. */
 	struct win_event ptr_events[8];
 	unsigned int ptr_head, ptr_tail;
+	/* Content-relative damage union since the WM last ACKed a present. */
+	unsigned int canvas_dmg_x, canvas_dmg_y;
+	unsigned int canvas_dmg_w, canvas_dmg_h;
 	/* Ring-3 WM content mapping/bookkeeping. */
 	unsigned int content_gen; /* bumped when the content kind/session changes */
 	unsigned int mapped_kind;
@@ -64,7 +67,7 @@ int  wm_server_begin(void);
 int  wm_server_present(const struct wm_present_info *in);
 int  wm_server_sync(void);
 int  wm_server_win_create(const struct win_create *in, struct win_info *out);
-int  wm_server_win_present(void);
+int  wm_server_win_present(const struct wm_win_present *in);
 int  wm_server_win_close(void);
 int  wm_server_win_info(struct win_info *out);
 int  wm_server_win_ack_resize(void);

+ 7 - 0
wm_abi.h

@@ -94,6 +94,13 @@ struct wm_window_info {
 	char title[16];
 };
 
+/* SYS_WIN_PRESENT argument: the content-relative part of the canvas that
+ * changed since the last present.  w == 0 or h == 0 means the whole canvas,
+ * so a caller that does not track damage keeps the old behaviour. */
+struct wm_win_present {
+	unsigned int x, y, w, h;
+};
+
 struct wm_map_info {
 	void *va;
 	unsigned int kind;