Skip to content

Commit 901ccc9

Browse files
committed
Merge remote-tracking branch 'origin/p516/warm-jit' into p516/warm-restore-depth
# Conflicts: # src/snapshot.ts
2 parents c6daf07 + 181c32e commit 901ccc9

14 files changed

Lines changed: 330 additions & 27 deletions

File tree

‎docs/browser.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ compile loads over a thousand) and no library handles are live. Later library
162162
starts with the same class path restore that image, after checking that the
163163
files, missing paths and directory listings those calls used are unchanged; the
164164
first javac compile after it took 2.7 s instead of 5.3 s in Chromium on a
165-
Raspberry Pi 5. An image is about 18 MB. IndexedDB keeps the 2 most recent warm images separately
165+
Raspberry Pi 5. An image is about 21 MB; it holds the JS the JIT generated for the methods compiled so far, and a restored method compiles that code on its first call. IndexedDB keeps the 2 most recent warm images separately
166166
from boot snapshots. With `debug: true`, the console says whether a VM was
167167
saved, skipped as busy (with the reason) or restored, and why a restore missed.
168168

‎docs/node.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,9 @@ compile loads over a thousand) and no library handles are live. A later library
7575
start with the same class path and working directory restores it, after
7676
checking that the files, missing paths and directory listings those calls used
7777
are unchanged; a javac compile from it takes about 1 s instead of 6 s on a
78-
Raspberry Pi 5. An image is about 18 MB; warm snapshots share the snapshot
78+
Raspberry Pi 5. An image is about 21 MB, as it also holds the JS the JIT generated for the
79+
methods compiled so far; a restored method compiles that code on its first
80+
call instead of generating it again. Warm snapshots share the snapshot
7981
directory and keep the 2 most recent. They build on boot snapshots, so with
8082
`snapshotDir: null` there are none.
8183

‎docs/support.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ java-web targets headless Java: console apps, libraries and javac.
99
- `java.desktop`'s headless parts work: 2D geometry, image pixels, `Graphics2D`
1010
drawing on a `BufferedImage`, and JavaBeans. So does `java.xml`, including
1111
XML Schema validation and DTDs from the JDK's built-in catalog.
12+
- File mappings are copies in the VM's 512 MB native memory, which is also
13+
shared with direct buffers and other native allocations. A mapping that does
14+
not fit fails with `IOException: Map failed` and an `OutOfMemoryError` cause.
15+
Read-write changes reach the file on force or unmap.
1216
- `Deflater` writes valid DEFLATE streams using stored blocks. Compression
1317
levels and strategies currently do not reduce output size; compressed bytes
1418
and compression ratios differ from HotSpot's zlib output.

‎src/jit.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { memberTarget } from "./natives/invoke.ts";
2222
import { concatStrings } from "./natives/strings.ts";
2323
import { Frame, JavaThrow, NativeFrame, PendingThrow, fromNative } from "./thread.ts";
2424
import type { JThread } from "./thread.ts";
25+
import type { JVM } from "./jvm.ts";
2526

2627
export const RET = 0, SUSPEND = 1;
2728
export type Compiled = (t: JThread, f: Frame) => number;
@@ -64,10 +65,26 @@ export function noteBackedge(t: JThread, m: JMethod) {
6465
if (m.hot >= BACKEDGE_THRESHOLD && m.jit === null && !m.noJit) compile(t, m);
6566
}
6667

68+
export interface SavedJit { src: string; consts: any[] }
69+
70+
// Gives m the code saved with a warm snapshot, compiled on its first call.
71+
export function restoreJit(vm: JVM, m: JMethod, code: SavedJit) {
72+
if (disabled || noInline || stats) return;
73+
vm.jitCode.set(m, code);
74+
m.hot = THRESHOLD - 1;
75+
}
76+
6777
function compile(t: JThread, m: JMethod) {
6878
if (disabled || m.noJit || !m.code || m.name === "<clinit>" || m.code.code.length > MAX_CODE) return;
79+
const vm = t.vm;
6980
try {
70-
const { src, consts } = generate(t, m);
81+
let code = vm.keepJit ? undefined : vm.jitCode.get(m);
82+
if (code) vm.jitCode.delete(m);
83+
else {
84+
code = generate(t, m);
85+
if (vm.keepJit && !stats && !noInline) vm.jitCode.set(m, code);
86+
}
87+
const { src, consts } = code;
7188
if (dump && m.toString().includes(dump)) console.error(`// ${m}\n${src}`);
7289
m.jit = new Function("rt", "K", src)(runtime, consts) as Compiled;
7390
if (stats) stats.set(`compiled ${m}`, src.length);

‎src/jvm.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import { hostNative, jniNames } from "./hostnatives.ts";
2525
import { Library } from "./library.ts";
2626
import { dumpVM, restoreVM, snapshotKey, SNAPSHOT_FORMAT } from "./snapshot.ts";
2727
import type { SnapshotImage, WarmSnapshotImage } from "./snapshot.ts";
28+
import type { SavedJit } from "./jit.ts";
2829
import type { LibraryRequest } from "./library.ts";
2930
import type { HostNative } from "./hostnatives.ts";
3031
import { PROXY_HOST, PROXY_PORT } from "./http-proxy.ts";
@@ -143,6 +144,10 @@ export class JVM {
143144
classCount = 0;
144145
// every class in creation order, until the snapshot after boot is taken
145146
created: JClass[] | null;
147+
// Generated JS of compiled methods: kept until the warm snapshot is saved,
148+
// then (after a warm restore) compiled on each method's first call.
149+
keepJit: boolean;
150+
jitCode = new Map<JMethod, SavedJit>();
146151
threadsStarted = 0;
147152
peakThreads = 0;
148153
exitCode: number | null = null;
@@ -159,6 +164,7 @@ export class JVM {
159164

160165
constructor(opts: JvmOptions) {
161166
this.created = opts.snapshots ? [] : null;
167+
this.keepJit = !!(opts.warmSnapshot && opts.warmSnapshots && opts.snapshots);
162168
this.opts = opts;
163169
this.fs = opts.fs;
164170
const extra = ipv4Literal(opts.hostName);
@@ -1158,6 +1164,8 @@ export class JVM {
11581164
if (!trace) {
11591165
this.fs.endWarmTrace();
11601166
this.warmTraceActive = false;
1167+
this.keepJit = false;
1168+
this.jitCode.clear();
11611169
this.debug("warm snapshot busy: access record too large");
11621170
return;
11631171
}
@@ -1169,6 +1177,8 @@ export class JVM {
11691177
this.fs.endWarmTrace();
11701178
this.warmTraceActive = false;
11711179
this.warmSaved = true;
1180+
this.keepJit = false;
1181+
this.jitCode.clear();
11721182
for (const c of this.created ?? []) c.bytes = undefined;
11731183
this.created = null;
11741184
this.debug("warm snapshot saved");
@@ -1264,6 +1274,7 @@ export class JVM {
12641274
return false;
12651275
}
12661276
try {
1277+
this.keepJit = false;
12671278
restoreVM(this, image, t);
12681279
this.warmRestored = true;
12691280
this.warmSaved = true;

‎src/memory.ts‎

Lines changed: 73 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { PendingThrow } from "./thread.ts";
66
const ALIGN = 16;
77
// Like a failed malloc in HotSpot, going past this throws OutOfMemoryError.
88
const LIMIT = 512 << 20;
9+
const MIN_SHRINK = 2 << 20;
910

1011
export class NativeMemory {
1112
buf: ArrayBuffer;
@@ -15,40 +16,79 @@ export class NativeMemory {
1516
private sizes = new Map<number, number>();
1617
// free blocks by size
1718
private free = new Map<number, number[]>();
19+
// end address to size, and start address to list index, for the free blocks
20+
private freeEnds = new Map<number, number>();
21+
private freeAt = new Map<number, number>();
22+
23+
private initial: number;
1824

1925
constructor(initial = 1 << 20) {
26+
this.initial = initial;
2027
this.buf = new ArrayBuffer(initial);
2128
this.u8 = new Uint8Array(this.buf);
2229
this.dv = new DataView(this.buf);
2330
}
2431

32+
private resize(size: number) {
33+
const next = new ArrayBuffer(size);
34+
new Uint8Array(next).set(this.u8.subarray(0, Math.min(this.top, size)));
35+
this.buf = next;
36+
this.u8 = new Uint8Array(next);
37+
this.dv = new DataView(next);
38+
}
39+
2540
private grow(need: number) {
2641
if (need > LIMIT) throw new PendingThrow("java/lang/OutOfMemoryError", `Unable to allocate ${need - this.buf.byteLength} bytes`);
2742
let size = this.buf.byteLength;
2843
while (size < need) size *= 2;
2944
size = Math.min(size, LIMIT);
30-
const next = new ArrayBuffer(size);
31-
new Uint8Array(next).set(this.u8);
32-
this.buf = next;
33-
this.u8 = new Uint8Array(next);
34-
this.dv = new DataView(next);
45+
try { this.resize(size); }
46+
catch (e) {
47+
if (e instanceof RangeError) throw new PendingThrow("java/lang/OutOfMemoryError", `Unable to allocate ${size} bytes`);
48+
throw e;
49+
}
50+
}
51+
52+
// The saved state of a snapshot: the bytes up to top and the block tables.
53+
restore(bytes: Uint8Array, top: number, sizes: Map<number, number>, free: Map<number, number[]>) {
54+
this.buf = new ArrayBuffer(Math.max(this.buf.byteLength, bytes.length));
55+
this.u8 = new Uint8Array(this.buf);
56+
this.dv = new DataView(this.buf);
57+
this.u8.set(bytes);
58+
this.top = top;
59+
this.sizes = sizes;
60+
this.free = free;
61+
this.freeEnds.clear();
62+
this.freeAt.clear();
63+
for (const [size, blocks] of free) {
64+
blocks.forEach((start, i) => { this.freeEnds.set(start + size, size); this.freeAt.set(start, i); });
65+
}
66+
}
67+
68+
// The order of a free list does not matter, so the last block fills the gap.
69+
private takeFree(size: number, list: number[], at: number): number {
70+
const addr = list[at];
71+
const last = list.pop()!;
72+
if (at < list.length) { list[at] = last; this.freeAt.set(last, at); }
73+
if (!list.length) this.free.delete(size);
74+
this.freeAt.delete(addr);
75+
this.freeEnds.delete(addr + size);
76+
return addr;
3577
}
3678

3779
malloc(n: number, alignment = ALIGN): number {
3880
const size = Math.max(ALIGN, Math.ceil(n / ALIGN) * ALIGN);
3981
const list = this.free.get(size);
4082
const reuse = list?.findIndex((addr) => addr % alignment === 0) ?? -1;
4183
if (list && reuse >= 0) {
42-
// the order of a free list does not matter, so the last block fills the gap
43-
const addr = list[reuse];
44-
list[reuse] = list[list.length - 1];
45-
list.pop();
84+
const addr = this.takeFree(size, list, reuse);
4685
this.sizes.set(addr, size);
4786
return addr;
4887
}
4988
const addr = Math.ceil(this.top / alignment) * alignment;
50-
this.top = addr + size;
51-
if (this.top > this.buf.byteLength) this.grow(this.top);
89+
const top = addr + size;
90+
if (top > this.buf.byteLength) this.grow(top);
91+
this.top = top;
5292
this.sizes.set(addr, size);
5393
return addr;
5494
}
@@ -57,9 +97,28 @@ export class NativeMemory {
5797
const size = this.sizes.get(addr);
5898
if (size === undefined) return;
5999
this.sizes.delete(addr);
60-
let list = this.free.get(size);
61-
if (!list) this.free.set(size, (list = []));
62-
list.push(addr);
100+
if (addr + size < this.top) {
101+
let list = this.free.get(size);
102+
if (!list) this.free.set(size, (list = []));
103+
this.freeAt.set(addr, list.push(addr) - 1);
104+
this.freeEnds.set(addr + size, size);
105+
return;
106+
}
107+
// Lower top over this block and any free blocks that end where it starts.
108+
let top = addr;
109+
for (let below = this.freeEnds.get(top); below !== undefined; below = this.freeEnds.get(top)) {
110+
top -= below;
111+
this.takeFree(below, this.free.get(below)!, this.freeAt.get(top)!);
112+
}
113+
this.top = Math.max(top, ALIGN);
114+
if (this.buf.byteLength >= MIN_SHRINK && this.top <= this.buf.byteLength / 4) {
115+
const size = Math.max(this.initial, 2 ** Math.ceil(Math.log2(this.top)));
116+
// best effort: a free must not fail
117+
if (size < this.buf.byteLength) {
118+
try { this.resize(size); }
119+
catch (e) { if (!(e instanceof RangeError)) throw e; }
120+
}
121+
}
63122
}
64123

65124
realloc(addr: number, n: number): number {

‎src/natives/nio.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ function writeBack(t: JThread, m: Mapping, base: number, addr: number, len: numb
333333
if (n <= 0) return true;
334334
const save = m.f.pos;
335335
m.f.pos = at;
336-
m.f.write(t.vm.mem.u8.slice(addr, addr + n), true);
336+
m.f.write(t.vm.mem.u8.subarray(addr, addr + n), true);
337337
m.f.pos = save;
338338
return flush(t, m.f);
339339
}
@@ -429,7 +429,13 @@ Object.assign(natives, {
429429
// writes only then.
430430
[`${UFD}map0(Ljava/io/FileDescriptor;IJJZ)J`]: (t: JThread, [fd, prot, pos, len]: any[]) => {
431431
const f = chanFile(t, fd);
432-
const addr = t.vm.mem.malloc(Number(len), 4096);
432+
let addr: number;
433+
try { addr = t.vm.mem.malloc(Number(len), 4096); }
434+
catch (e) {
435+
// FileChannelImpl retries once, then wraps this in IOException("Map failed")
436+
if (e instanceof PendingThrow) throw new PendingThrow("java/lang/OutOfMemoryError", "Map failed");
437+
throw e;
438+
}
433439
const save = f.pos;
434440
f.pos = Number(pos);
435441
const n = Math.min(f.size - Number(pos), Number(len));

‎src/snapshot.ts‎

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { MAX_HEAP } from "./runtime.ts";
1212
import type { WarmTrace } from "./fs.ts";
1313
import { reopenSnapshotFile, OpenFile, streams } from "./natives/io.ts";
1414
import { JArray, JClass, JField, JMethod, JObject, Monitor } from "./runtime.ts";
15+
import { restoreJit } from "./jit.ts";
1516
import { Frame, JThread, NativeFrame, STATUS_RUNNABLE } from "./thread.ts";
1617
import type { NativeGen } from "./thread.ts";
1718

@@ -53,6 +54,8 @@ interface ClassRec {
5354
nestHost: unknown;
5455
links: [string, unknown][];
5556
caches: [string, unknown][];
57+
// generated JS and constants of compiled methods, in warm snapshots
58+
jit?: [string, string, unknown][];
5659
}
5760

5861
interface VmRec {
@@ -134,6 +137,25 @@ class Encoder {
134137
}
135138

136139
private work: (() => void)[] = [];
140+
private undo: { twins: unknown[]; table: number } | null = null;
141+
142+
// enc, or null with nothing recorded when v cannot be saved
143+
tryEnc(v: any, path: string): any {
144+
const undo = (this.undo = { twins: [] as unknown[], table: this.table.length });
145+
try {
146+
return this.enc(v, path);
147+
} catch {
148+
this.work.length = 0;
149+
for (const k of undo.twins) {
150+
this.leaves.delete(this.twins.get(k));
151+
this.twins.delete(k);
152+
}
153+
for (const t of this.table.splice(undo.table)) this.named.delete(t);
154+
return null;
155+
} finally {
156+
this.undo = null;
157+
}
158+
}
137159

138160
// The twin of v, or a reference to it if it has one already. Containers are
139161
// filled in by drain, so deep object graphs need no deep recursion.
@@ -255,6 +277,7 @@ class Encoder {
255277
});
256278
}
257279
this.twins.set(v, t);
280+
this.undo?.twins.push(v);
258281
if (!(v instanceof JObject) ? v instanceof JClass || v instanceof JMethod || v instanceof JField || v instanceof JThread : this.isLeaf(v)) this.leaves.add(t);
259282
return t;
260283
}
@@ -381,6 +404,15 @@ export function dumpVM(vm: JVM, main: JThread, key: string, library = false): Sn
381404
links: c.methods.filter((m) => m.link).map((m) => [m.key, e.enc(m.link, `${p}.${m.key}.link`)]),
382405
caches: c.methods.filter((m) => m.cache).map((m) => [m.key, e.enc(m.cache, `${p}.${m.key}.cache`)]),
383406
};
407+
if (library) {
408+
const jit: [string, string, unknown][] = [];
409+
for (const m of c.methods) {
410+
const code = m.jit && vm.jitCode.get(m);
411+
const consts = code && e.tryEnc(code.consts, `${p}.${m.key}.jit`);
412+
if (code && consts) jit.push([m.key, code.src, consts]);
413+
}
414+
if (jit.length) rec.jit = jit;
415+
}
384416
if (c.initThread || c.initWaiters.length) throw new Error(`snapshot: ${c.name} is being initialized`);
385417
if (rec.kind === "prim") rec.desc = c.prim!;
386418
else if (rec.kind === "array") rec.component = e.cls(c.component!, p);
@@ -507,6 +539,7 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) {
507539
c.nestHost = d.dec(r.nestHost);
508540
for (const [k, l] of r.links) c.methodMap.get(k)!.link = d.dec(l);
509541
for (const [k, cache] of r.caches ?? []) c.methodMap.get(k)!.cache = d.dec(cache);
542+
for (const [k, src, consts] of r.jit ?? []) restoreJit(vm, c.methodMap.get(k)!, { src, consts: d.dec(consts) });
510543
});
511544
d.flush();
512545
const v = image.vm;
@@ -527,14 +560,7 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) {
527560
vm.state.set(k, { next: fds.next, files });
528561
} else vm.state.set(k, d.dec(x));
529562
}
530-
const mem = vm.mem as any;
531-
mem.buf = new ArrayBuffer(Math.max(mem.buf.byteLength, v.mem.buf.length));
532-
mem.u8 = new Uint8Array(mem.buf);
533-
mem.dv = new DataView(mem.buf);
534-
mem.u8.set(v.mem.buf);
535-
mem.top = v.mem.top;
536-
mem.sizes = d.dec(v.mem.sizes);
537-
mem.free = d.dec(v.mem.free);
563+
vm.mem.restore(v.mem.buf, v.mem.top, d.dec(v.mem.sizes), d.dec(v.mem.free));
538564
d.flush();
539565

540566
const mainRec = image.threads[0];

0 commit comments

Comments
 (0)