diff --git a/tools/xfer-bench/.gitignore b/tools/xfer-bench/.gitignore new file mode 100644 index 000000000..a7e04a21b --- /dev/null +++ b/tools/xfer-bench/.gitignore @@ -0,0 +1,4 @@ +.gradle/ +build/ +app/build/ +local.properties diff --git a/tools/xfer-bench/README.md b/tools/xfer-bench/README.md new file mode 100644 index 000000000..2ef42a140 --- /dev/null +++ b/tools/xfer-bench/README.md @@ -0,0 +1,34 @@ +# xfer-bench + +Test APK for K2GO-576: how fast two phones move data over TCP (Java copy loops) and over a +USB cable (Android Open Accessory). It is a measurement tool, not part of K2Go. It is never +published. Results: . + +Build (from this folder, in a host terminal): + +``` +.\gradlew.bat assembleDebug +adb install -r app\build\outputs\apk\debug\app-debug.apk +``` + +Drive it with adb. Each result goes to logcat (tag `XferBench`) and to `files/results.txt`. + +| Command | Extras | +| --- | --- | +| `tcp-recv` | `port` (5301), `method` (`kernel`, `direct`, `stream`), `sink` (`null`, `int`, `ext`), `bufkb` (256) | +| `tcp-send` | `host`, `port`, `method`, `pattern` (`zeros`, `ones`, `alt`), `mb` (long), `src` (`pattern`, `int`, `ext`) | +| `prep` | `at` (`int`, `ext`), `pattern`, `mb`: writes `src.bin` for a file send | +| `aoa-host` | `dir` (`S` host sends, `R` host receives), `pattern`, `mb`, `buf` (bytes per bulk transfer) | +| `aoa-acc` | `buf`: serve the host (also starts by itself when the host switches the phone to accessory mode) | + +Example: + +``` +adb shell am start -n org.appdevforall.xferbench/.MainActivity --es cmd tcp-recv --es method kernel --es sink int +adb shell am start -n org.appdevforall.xferbench/.MainActivity --es cmd tcp-send --es host 192.168.1.66 --el mb 1024 +``` + +`method=kernel` uses `FileChannel.transferTo` (sendfile) on the sender and `transferFrom` on the +receiver. `sink=int` writes to app-private storage, `sink=ext` to the app folder on shared +storage (FUSE). For AOA, run `aoa-host` on the phone that is the USB host (`dumpsys usb`) and +accept the USB dialogs on both phones. diff --git a/tools/xfer-bench/app/build.gradle b/tools/xfer-bench/app/build.gradle new file mode 100644 index 000000000..1c5eaa03c --- /dev/null +++ b/tools/xfer-bench/app/build.gradle @@ -0,0 +1,19 @@ +apply plugin: 'com.android.application' + +android { + namespace 'org.appdevforall.xferbench' + compileSdk 36 + + defaultConfig { + applicationId 'org.appdevforall.xferbench' + minSdk 26 + targetSdk 36 + versionCode 1 + versionName '0.1' + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } +} diff --git a/tools/xfer-bench/app/src/main/AndroidManifest.xml b/tools/xfer-bench/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..c17cb8bcc --- /dev/null +++ b/tools/xfer-bench/app/src/main/AndroidManifest.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/AoaBench.java b/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/AoaBench.java new file mode 100644 index 000000000..14dac91cb --- /dev/null +++ b/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/AoaBench.java @@ -0,0 +1,164 @@ +package org.appdevforall.xferbench; + +import android.hardware.usb.UsbAccessory; +import android.hardware.usb.UsbConstants; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbDeviceConnection; +import android.hardware.usb.UsbEndpoint; +import android.hardware.usb.UsbInterface; +import android.hardware.usb.UsbManager; +import android.os.ParcelFileDescriptor; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +/** + * Android Open Accessory (AOA) byte stream between two phones, for K2GO-576 step 2. + * The USB host phone switches the other phone into accessory mode, then both sides + * move raw bytes over the bulk endpoints. Protocol: the host sends a 10-byte header + * (command, pattern, length); 'S' = host sends, 'R' = host receives. + * Spec: https://source.android.com/docs/core/interaction/accessories/aoa + */ +final class AoaBench { + private static final int GOOGLE_VID = 0x18D1; + private static final int AOA_GET_PROTOCOL = 51; + private static final int AOA_SEND_STRING = 52; + private static final int AOA_START = 53; + // Must match res/xml/accessory_filter.xml (manufacturer, model, version). + private static final String[] IDS = {"AppDevForAll", "XferBench", "K2Go transfer benchmark", "1", + "https://appdevforall.org", "0"}; + private static final int HEADER = 10; + private static final int TIMEOUT_MS = 5000; + + interface Log { void line(String s); } + + private AoaBench() {} + + static boolean isAccessoryMode(UsbDevice d) { + return d.getVendorId() == GOOGLE_VID && d.getProductId() >= 0x2D00 && d.getProductId() <= 0x2D05; + } + + /** Asks the attached phone to restart its USB function in accessory mode. Returns the AOA version. */ + static int switchToAccessory(UsbManager um, UsbDevice d) throws IOException { + UsbDeviceConnection c = um.openDevice(d); + if (c == null) throw new IOException("openDevice failed"); + try { + byte[] v = new byte[2]; + if (c.controlTransfer(0xC0, AOA_GET_PROTOCOL, 0, 0, v, 2, 1000) < 2) { + throw new IOException("the other phone does not answer AOA GET_PROTOCOL"); + } + for (int i = 0; i < IDS.length; i++) { + byte[] s = (IDS[i] + "\0").getBytes(StandardCharsets.UTF_8); + if (c.controlTransfer(0x40, AOA_SEND_STRING, 0, i, s, s.length, 1000) < 0) { + throw new IOException("AOA SEND_STRING " + i + " failed"); + } + } + if (c.controlTransfer(0x40, AOA_START, 0, 0, null, 0, 1000) < 0) { + throw new IOException("AOA START failed"); + } + return (v[1] & 0xFF) << 8 | (v[0] & 0xFF); + } finally { + c.close(); + } + } + + /** Host side, with the other phone already in accessory mode. */ + static String host(UsbManager um, UsbDevice d, char cmd, String pattern, long mb, int buf) throws IOException { + UsbDeviceConnection c = um.openDevice(d); + if (c == null) throw new IOException("openDevice failed (accessory mode)"); + UsbInterface intf = d.getInterface(0); + try { + if (!c.claimInterface(intf, true)) throw new IOException("claimInterface failed"); + UsbEndpoint in = null, out = null; + for (int i = 0; i < intf.getEndpointCount(); i++) { + UsbEndpoint e = intf.getEndpoint(i); + if (e.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) continue; + if (e.getDirection() == UsbConstants.USB_DIR_IN) in = e; else out = e; + } + if (in == null || out == null) throw new IOException("no bulk endpoints"); + long total = mb << 20; + ByteBuffer h = ByteBuffer.allocate(HEADER); + h.put((byte) cmd).put((byte) pattern.charAt(0)).putLong(total); + if (c.bulkTransfer(out, h.array(), HEADER, TIMEOUT_MS) != HEADER) throw new IOException("header failed"); + + byte[] b = Payload.fill(pattern, buf); + long n = 0, t0 = System.nanoTime(); + if (cmd == 'S') { + while (n < total) { + int r = c.bulkTransfer(out, b, (int) Math.min(b.length, total - n), TIMEOUT_MS); + if (r < 0) throw new IOException("bulk OUT failed after " + n + " bytes"); + n += r; + } + long dt = System.nanoTime() - t0; + byte[] ack = new byte[16384]; + int r = c.bulkTransfer(in, ack, ack.length, 20000); + String acc = r >= 8 ? String.format(java.util.Locale.ROOT, " accessorySecs=%.2f", + ByteBuffer.wrap(ack, 0, 8).getLong() / 1e9) : " (no ack)"; + return TcpBench.result("aoa-host-send", "bulk" + buf, pattern, n, dt) + acc; + } + while (n < total) { + int r = c.bulkTransfer(in, b, b.length, TIMEOUT_MS); + if (r < 0) throw new IOException("bulk IN failed after " + n + " bytes"); + n += r; + } + return TcpBench.result("aoa-host-recv", "bulk" + buf, "accessory", n, System.nanoTime() - t0); + } finally { + c.releaseInterface(intf); + c.close(); + } + } + + /** Accessory side: serves host commands until the cable is unplugged or the host closes. */ + static void accessory(UsbManager um, UsbAccessory a, int buf, Log log) throws IOException { + ParcelFileDescriptor pfd = um.openAccessory(a); + if (pfd == null) throw new IOException("openAccessory failed"); + try (FileInputStream in = new FileInputStream(pfd.getFileDescriptor()); + FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor())) { + // f_accessory reads need a buffer of at least 16 KiB. + byte[] b = new byte[Math.max(buf, 16384)]; + log.line("accessory: ready, waiting for the host"); + while (true) { + int r = in.read(b); + if (r < 0) break; + if (r < HEADER) { log.line("accessory: short header " + r); continue; } + ByteBuffer h = ByteBuffer.wrap(b, 0, HEADER); + char cmd = (char) h.get(); + String pattern = patternName((char) h.get()); + long total = h.getLong(); + long t0 = System.nanoTime(); + if (cmd == 'S') { + long n = r - HEADER; + while (n < total) { + int k = in.read(b); + if (k < 0) throw new IOException("accessory read ended after " + n + " bytes"); + n += k; + } + long dt = System.nanoTime() - t0; + out.write(ByteBuffer.allocate(8).putLong(dt).array()); + log.line(TcpBench.result("aoa-acc-recv", "read" + b.length, pattern, n, dt)); + } else if (cmd == 'R') { + byte[] data = Payload.fill(pattern, b.length); + long n = 0; + while (n < total) { + int len = (int) Math.min(data.length, total - n); + out.write(data, 0, len); + n += len; + } + log.line(TcpBench.result("aoa-acc-send", "write" + data.length, pattern, n, System.nanoTime() - t0)); + } else { + break; + } + } + } finally { + pfd.close(); + log.line("accessory: closed"); + } + } + + private static String patternName(char c) { + return c == 'o' ? "ones" : c == 'a' ? "alt" : "zeros"; + } +} diff --git a/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/MainActivity.java b/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/MainActivity.java new file mode 100644 index 000000000..1e95e81bd --- /dev/null +++ b/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/MainActivity.java @@ -0,0 +1,236 @@ +package org.appdevforall.xferbench; + +import android.app.Activity; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.hardware.usb.UsbAccessory; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbManager; +import android.net.wifi.WifiManager; +import android.os.Build; +import android.os.Bundle; +import android.os.PowerManager; +import android.util.Log; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * K2GO-576 transfer benchmark. Driven by adb, for example: + * am start -n org.appdevforall.xferbench/.MainActivity --es cmd tcp-recv --es method kernel --es sink int + * am start -n org.appdevforall.xferbench/.MainActivity --es cmd tcp-send --es host 192.168.1.66 --el mb 1024 + * am start -n org.appdevforall.xferbench/.MainActivity --es cmd aoa-host --es dir S --el mb 256 --ei buf 16384 + * Each result goes to logcat (tag XferBench), to the screen and to files/results.txt. + */ +public class MainActivity extends Activity { + private static final String TAG = "XferBench"; + private static final String ACTION_USB_PERMISSION = "org.appdevforall.xferbench.USB_PERMISSION"; + + private TextView logView; + private UsbManager usb; + + @Override + protected void onCreate(Bundle state) { + super.onCreate(state); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + usb = (UsbManager) getSystemService(Context.USB_SERVICE); + + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + int pad = (int) (16 * getResources().getDisplayMetrics().density); + root.setPadding(pad, pad, pad, pad); + root.addView(button("AOA host: send 256 MiB", () -> aoaHost('S', "zeros", 256, 16384))); + root.addView(button("AOA host: receive 256 MiB", () -> aoaHost('R', "zeros", 256, 16384))); + root.addView(button("AOA accessory: wait for host", () -> aoaAccessory(null, 16384))); + logView = new TextView(this); + logView.setTextIsSelectable(true); + ScrollView sv = new ScrollView(this); + sv.addView(logView); + root.addView(sv); + setContentView(root); + handle(getIntent()); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + setIntent(intent); + handle(intent); + } + + private void handle(Intent i) { + if (i == null) return; + if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(i.getAction())) { + UsbAccessory a = i.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); + run(() -> aoaAccessory(a, 16384)); + return; + } + String cmd = i.getStringExtra("cmd"); + if (cmd == null) return; + String method = str(i, "method", "kernel"); + String pattern = str(i, "pattern", "zeros"); + long mb = i.getLongExtra("mb", 1024); + int bufKb = i.getIntExtra("bufkb", 256); + int port = i.getIntExtra("port", 5301); + switch (cmd) { + case "tcp-recv": + run(() -> log(TcpBench.receive(port, method, sink(str(i, "sink", "null")), bufKb))); + break; + case "tcp-send": + String src = str(i, "src", "pattern"); + run(() -> log(TcpBench.send(str(i, "host", ""), port, method, pattern, mb, + "pattern".equals(src) ? null : new File(dir(src), "src.bin"), bufKb))); + break; + case "prep": + run(() -> log(TcpBench.prepare(new File(dir(str(i, "at", "int")), "src.bin"), pattern, mb))); + break; + case "aoa-host": + char dirCmd = str(i, "dir", "S").charAt(0); + int buf = i.getIntExtra("buf", 16384); + run(() -> aoaHost(dirCmd, pattern, mb, buf)); + break; + case "aoa-acc": + run(() -> aoaAccessory(null, i.getIntExtra("buf", 16384))); + break; + default: + log("unknown cmd " + cmd); + } + } + + private static String str(Intent i, String k, String def) { + String v = i.getStringExtra(k); + return v == null ? def : v; + } + + /** "int" = app-private storage, "ext" = app folder on shared storage (FUSE). */ + private File dir(String at) { + return "ext".equals(at) ? getExternalFilesDir(null) : getFilesDir(); + } + + private File sink(String at) { + return "null".equals(at) ? null : new File(dir(at), "sink.bin"); + } + + // ---------------------------------------------------------------- AOA + + private void aoaHost(char cmd, String pattern, long mb, int buf) throws Exception { + UsbDevice d = findDevice(); + if (d == null) { log("aoa-host: no USB device. Is this phone the USB host?"); return; } + if (!AoaBench.isAccessoryMode(d)) { + if (!permission(d)) { log("aoa-host: permission denied"); return; } + int proto = AoaBench.switchToAccessory(usb, d); + log("aoa-host: AOA version " + proto + ", waiting for accessory mode"); + d = waitForAccessoryMode(); + if (d == null) { log("aoa-host: the other phone did not come back in accessory mode"); return; } + Thread.sleep(1500); // let the accessory app open its end + } + if (!permission(d)) { log("aoa-host: permission denied (accessory mode)"); return; } + log(AoaBench.host(usb, d, cmd, pattern, mb, buf)); + } + + private void aoaAccessory(UsbAccessory a, int buf) throws Exception { + if (a == null) { + UsbAccessory[] list = usb.getAccessoryList(); + if (list == null || list.length == 0) { log("aoa-acc: no accessory. Start AOA on the host phone first"); return; } + a = list[0]; + } + if (!usb.hasPermission(a) && !permission(a)) { log("aoa-acc: permission denied"); return; } + AoaBench.accessory(usb, a, buf, this::log); + } + + private UsbDevice findDevice() { + UsbDevice any = null; + for (UsbDevice d : usb.getDeviceList().values()) { + if (AoaBench.isAccessoryMode(d)) return d; + any = d; + } + return any; + } + + private UsbDevice waitForAccessoryMode() throws InterruptedException { + for (int i = 0; i < 60; i++) { + Thread.sleep(250); + for (UsbDevice d : usb.getDeviceList().values()) if (AoaBench.isAccessoryMode(d)) return d; + } + return null; + } + + private boolean permission(Object target) throws InterruptedException { + if (target instanceof UsbDevice && usb.hasPermission((UsbDevice) target)) return true; + CountDownLatch latch = new CountDownLatch(1); + boolean[] ok = {false}; + BroadcastReceiver r = new BroadcastReceiver() { + @Override public void onReceive(Context c, Intent i) { + ok[0] = i.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false); + latch.countDown(); + } + }; + IntentFilter f = new IntentFilter(ACTION_USB_PERMISSION); + if (Build.VERSION.SDK_INT >= 33) registerReceiver(r, f, Context.RECEIVER_NOT_EXPORTED); + else registerReceiver(r, f); + try { + PendingIntent pi = PendingIntent.getBroadcast(this, 0, + new Intent(ACTION_USB_PERMISSION).setPackage(getPackageName()), + PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); + log("waiting for the USB permission dialog"); + if (target instanceof UsbDevice) usb.requestPermission((UsbDevice) target, pi); + else usb.requestPermission((UsbAccessory) target, pi); + latch.await(60, TimeUnit.SECONDS); + } finally { + unregisterReceiver(r); + } + return ok[0]; + } + + // ---------------------------------------------------------------- plumbing + + interface Job { void run() throws Exception; } + + private Button button(String label, Job job) { + Button b = new Button(this); + b.setText(label); + b.setOnClickListener(v -> run(job)); + return b; + } + + @SuppressWarnings("deprecation") // WIFI_MODE_FULL_HIGH_PERF: the same lock K2Go Clone holds + private void run(Job job) { + new Thread(() -> { + PowerManager.WakeLock wl = ((PowerManager) getSystemService(POWER_SERVICE)) + .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XferBench:run"); + WifiManager.WifiLock fl = ((WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE)) + .createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "XferBench:run"); + wl.acquire(30 * 60 * 1000L); + fl.acquire(); + try { + job.run(); + } catch (Exception e) { + log("error: " + e); + } finally { + fl.release(); + wl.release(); + } + }, "xfer-bench").start(); + } + + private void log(String s) { + Log.i(TAG, s); + runOnUiThread(() -> logView.append(s + "\n")); + try (FileWriter w = new FileWriter(new File(getFilesDir(), "results.txt"), true)) { + w.write(System.currentTimeMillis() + " " + s + "\n"); + } catch (IOException ignored) { + // the logcat line is the record + } + } +} diff --git a/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/Payload.java b/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/Payload.java new file mode 100644 index 000000000..22c256c11 --- /dev/null +++ b/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/Payload.java @@ -0,0 +1,18 @@ +package org.appdevforall.xferbench; + +import java.util.Arrays; + +/** Test data patterns from K2GO-576 step 2: all zero, all one, alternating bits. */ +final class Payload { + private Payload() {} + + static byte[] fill(String pattern, int size) { + byte[] b = new byte[size]; + switch (pattern) { + case "ones": Arrays.fill(b, (byte) 0xFF); break; + case "alt": Arrays.fill(b, (byte) 0x55); break; + default: break; // zeros + } + return b; + } +} diff --git a/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/TcpBench.java b/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/TcpBench.java new file mode 100644 index 000000000..8cac1b34c --- /dev/null +++ b/tools/xfer-bench/app/src/main/java/org/appdevforall/xferbench/TcpBench.java @@ -0,0 +1,179 @@ +package org.appdevforall.xferbench; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; + +/** + * Raw TCP throughput from Java, for K2GO-576 (steps 2 and 3). + * Methods: "stream" (byte[] via java.io), "direct" (one direct ByteBuffer), + * "kernel" (FileChannel.transferTo / transferFrom: sendfile on the sender). + */ +final class TcpBench { + private static final long CHUNK = 4L << 20; + + private TcpBench() {} + + /** Accepts one connection on {@code port} and reads until EOF. sinkFile null = discard. */ + static String receive(int port, String method, File sinkFile, int bufKb) throws IOException { + try (ServerSocketChannel server = ServerSocketChannel.open()) { + server.socket().setReuseAddress(true); + server.bind(new InetSocketAddress(port)); + try (SocketChannel ch = server.accept()) { + long t0 = System.nanoTime(); + long n; + if (sinkFile == null) { + n = readDiscard(ch, method, bufKb); + } else { + try (RandomAccessFile raf = new RandomAccessFile(sinkFile, "rw"); + FileChannel fc = raf.getChannel()) { + n = readToFile(ch, fc, method, bufKb); + fc.force(false); + } finally { + //noinspection ResultOfMethodCallIgnored + sinkFile.delete(); + } + } + return result("tcp-recv", method, sinkFile == null ? "null" : sinkFile.getParent(), n, System.nanoTime() - t0); + } + } + } + + /** Connects and sends {@code mb} MiB of {@code pattern}, or the whole {@code srcFile} when it is not null. */ + static String send(String host, int port, String method, String pattern, long mb, File srcFile, int bufKb) + throws IOException { + try (SocketChannel ch = SocketChannel.open(new InetSocketAddress(host, port))) { + long t0 = System.nanoTime(); + long n = srcFile == null ? sendPattern(ch, method, pattern, mb << 20, bufKb) + : sendFile(ch, method, srcFile, bufKb); + ch.shutdownOutput(); + String src = srcFile == null ? pattern : srcFile.getParent(); + return result("tcp-send", method, src, n, System.nanoTime() - t0); + } + } + + /** Writes {@code mb} MiB of {@code pattern} to {@code f}, so "send" can read a real file. */ + static String prepare(File f, String pattern, long mb) throws IOException { + byte[] b = Payload.fill(pattern, 1 << 20); + long t0 = System.nanoTime(); + try (FileOutputStream out = new FileOutputStream(f)) { + for (long i = 0; i < mb; i++) out.write(b); + out.getFD().sync(); + } + return result("prepare", pattern, f.getParent(), mb << 20, System.nanoTime() - t0); + } + + private static long readDiscard(SocketChannel ch, String method, int bufKb) throws IOException { + long n = 0; + if ("stream".equals(method)) { + InputStream in = ch.socket().getInputStream(); + byte[] b = new byte[bufKb << 10]; + for (int r; (r = in.read(b)) > 0; ) n += r; + } else { + ByteBuffer bb = ByteBuffer.allocateDirect(bufKb << 10); + for (int r; (r = ch.read(bb)) >= 0; bb.clear()) n += r; + } + return n; + } + + private static long readToFile(SocketChannel ch, FileChannel fc, String method, int bufKb) throws IOException { + long n = 0; + switch (method) { + case "kernel": { + // transferFrom can return 0 before the end of a socket stream on Android: only a + // read of -1 means the sender is done. + ByteBuffer one = ByteBuffer.allocate(1); + while (true) { + long t = fc.transferFrom(ch, n, CHUNK); + if (t > 0) { n += t; continue; } + one.clear(); + if (ch.read(one) < 0) break; + one.flip(); + n += fc.write(one, n); + } + break; + } + case "stream": { + InputStream in = ch.socket().getInputStream(); + OutputStream out = java.nio.channels.Channels.newOutputStream(fc); + byte[] b = new byte[bufKb << 10]; + for (int r; (r = in.read(b)) > 0; ) { out.write(b, 0, r); n += r; } + break; + } + default: { + ByteBuffer bb = ByteBuffer.allocateDirect(bufKb << 10); + for (int r; (r = ch.read(bb)) >= 0; ) { + bb.flip(); + while (bb.hasRemaining()) fc.write(bb); + bb.clear(); + n += r; + } + } + } + return n; + } + + private static long sendPattern(SocketChannel ch, String method, String pattern, long total, int bufKb) + throws IOException { + byte[] b = Payload.fill(pattern, bufKb << 10); + long n = 0; + if ("stream".equals(method)) { + OutputStream out = ch.socket().getOutputStream(); + while (n < total) { int len = (int) Math.min(b.length, total - n); out.write(b, 0, len); n += len; } + out.flush(); + } else { + ByteBuffer bb = ByteBuffer.allocateDirect(b.length); + bb.put(b); + while (n < total) { + bb.clear(); + bb.limit((int) Math.min(bb.capacity(), total - n)); + while (bb.hasRemaining()) n += ch.write(bb); + } + } + return n; + } + + private static long sendFile(SocketChannel ch, String method, File f, int bufKb) throws IOException { + long n = 0; + try (FileInputStream fis = new FileInputStream(f); FileChannel fc = fis.getChannel()) { + long size = fc.size(); + switch (method) { + case "kernel": + while (n < size) n += fc.transferTo(n, Math.min(CHUNK, size - n), ch); + break; + case "stream": { + OutputStream out = ch.socket().getOutputStream(); + byte[] b = new byte[bufKb << 10]; + for (int r; (r = fis.read(b)) > 0; ) { out.write(b, 0, r); n += r; } + out.flush(); + break; + } + default: { + ByteBuffer bb = ByteBuffer.allocateDirect(bufKb << 10); + for (int r; (r = fc.read(bb)) > 0; ) { + bb.flip(); + while (bb.hasRemaining()) ch.write(bb); + bb.clear(); + n += r; + } + } + } + } + return n; + } + + static String result(String what, String method, String where, long bytes, long nanos) { + double s = nanos / 1e9; + return String.format(java.util.Locale.ROOT, "%s method=%s at=%s bytes=%d secs=%.2f MBps=%.1f", + what, method, where, bytes, s, bytes / 1e6 / s); + } +} diff --git a/tools/xfer-bench/app/src/main/res/xml/accessory_filter.xml b/tools/xfer-bench/app/src/main/res/xml/accessory_filter.xml new file mode 100644 index 000000000..03ef40ef5 --- /dev/null +++ b/tools/xfer-bench/app/src/main/res/xml/accessory_filter.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tools/xfer-bench/build.gradle b/tools/xfer-bench/build.gradle new file mode 100644 index 000000000..b0fff8ec6 --- /dev/null +++ b/tools/xfer-bench/build.gradle @@ -0,0 +1,17 @@ +// Standalone test APK for K2GO-576. Same AGP as controller/ so the Gradle cache is reused. +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.9.1' + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} diff --git a/tools/xfer-bench/gradle.properties b/tools/xfer-bench/gradle.properties new file mode 100644 index 000000000..36d494050 --- /dev/null +++ b/tools/xfer-bench/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +android.useAndroidX=false diff --git a/tools/xfer-bench/gradle/wrapper/gradle-wrapper.jar b/tools/xfer-bench/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e6441136f Binary files /dev/null and b/tools/xfer-bench/gradle/wrapper/gradle-wrapper.jar differ diff --git a/tools/xfer-bench/gradle/wrapper/gradle-wrapper.properties b/tools/xfer-bench/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..7dbd4a784 --- /dev/null +++ b/tools/xfer-bench/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +distributionSha256Sum=f397b287023acdba1e9f6fc5ea72d22dd63669d59ed4a289a29b1a76eee151c6 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/tools/xfer-bench/gradlew b/tools/xfer-bench/gradlew new file mode 100644 index 000000000..83f2acfdc --- /dev/null +++ b/tools/xfer-bench/gradlew @@ -0,0 +1,188 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/tools/xfer-bench/gradlew.bat b/tools/xfer-bench/gradlew.bat new file mode 100644 index 000000000..9618d8d96 --- /dev/null +++ b/tools/xfer-bench/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/tools/xfer-bench/settings.gradle b/tools/xfer-bench/settings.gradle new file mode 100644 index 000000000..01dffd405 --- /dev/null +++ b/tools/xfer-bench/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = "xfer-bench" +include ':app'