diff --git a/overlay/rootfs/etc/conf.d/geminux-hwinit b/overlay/rootfs/etc/conf.d/geminux-hwinit index e9398db..a7050a4 100644 --- a/overlay/rootfs/etc/conf.d/geminux-hwinit +++ b/overlay/rootfs/etc/conf.d/geminux-hwinit @@ -8,4 +8,5 @@ GEMINUX_ENABLE_MEDIATEK_DRM="yes" GEMINUX_ENABLE_CPUFREQ="yes" GEMINUX_ENABLE_SENSORS="no" GEMINUX_GATE_UNUSED_CLOCKS="yes" +GEMINUX_ENABLE_SPM_SLEEP="yes" GEMINUX_ENABLE_A72="no" diff --git a/overlay/rootfs/etc/init.d/geminux-hwinit b/overlay/rootfs/etc/init.d/geminux-hwinit index faa5701..50c219d 100755 --- a/overlay/rootfs/etc/init.d/geminux-hwinit +++ b/overlay/rootfs/etc/init.d/geminux-hwinit @@ -112,5 +112,9 @@ start() { load_group gate_unused mt6797-gate-unused fi + if [ "${GEMINUX_ENABLE_SPM_SLEEP:-yes}" = "yes" ]; then + load_group spm_sleep mt6797-spm-sleep + fi + eend 0 } diff --git a/overlay/rootfs/etc/modprobe.d/geminux.conf b/overlay/rootfs/etc/modprobe.d/geminux.conf index b473068..a10008c 100644 --- a/overlay/rootfs/etc/modprobe.d/geminux.conf +++ b/overlay/rootfs/etc/modprobe.d/geminux.conf @@ -1,4 +1,6 @@ # Enforce MT6797X safe hardware initialization order +options mt6797_spm_sleep sodi_idle=0 pmic_modes=1 timer_sec=600 +options mt6797_wlan power_save=0 softdep cpufreq_dt pre: clk_mt6797_mcusys softdep mtk_cci_devfreq pre: clk_mt6797_mcusys softdep mediatek_drm pre: clk_mt6797_mm mtk_mmsys mtk_mutex phy_mtk_mipi_dsi_drv panel_novatek_nt36672e diff --git a/overlay/rootfs/usr/bin/geminux-sync-dunst-theme b/overlay/rootfs/usr/bin/geminux-sync-dunst-theme index 062d677..55a6beb 100755 --- a/overlay/rootfs/usr/bin/geminux-sync-dunst-theme +++ b/overlay/rootfs/usr/bin/geminux-sync-dunst-theme @@ -63,17 +63,21 @@ cat > "$OUT_CONF.tmp" < "$OUT_CONF.tmp" < +Subject: [PATCH] geminux: fix SSD2092 wake, MT6351 fuel-gauge accuracy, and SPM standby + +- Ensure mtk_dsi holds WAKEUP_EN >= 1 ms on ULPS exit, stays in LP mode + through LPM panel init before enabling HS clock for video mode, skips + redundant 500 ms VM_DONE waits when already in CMD_MODE, and avoids + restarting video mode while dsi->enabled is false. +- Send the vendor Solomon SSD2092 register initialization sequence on + adopted wake when waking from sleep, and match the 50 ms display-on settle. +- Defer Solomon SSD2092 touch resume (.complete + 60 ms) until after DRM + wakes the display, using vendor DS_CUP_CONTROL (0x0002) LPM wake retries + without pulsing shared TDDI reset GPIO68 while display is active. +- Reject stale MT6351 AUXADC_ADC21 start-up OCV across warm reboots/reflashes, + scale reported capacity properly across [empty_pct .. full], and refresh + empty/untrusted anchors when userspace restores learned_resistance_uohm. +- Enable mt6797-spm-sleep hardware suspend loop, power down unlit AW9120 LEDs + during suspend, and clear INFRA_AO_MD_SRCCLKENA when CCCI MD1 stays gated. + +--- +diff --git a/drivers/gpu/drm/mediatek/mtk_dsi.c b/drivers/gpu/drm/mediatek/mtk_dsi.c +--- a/drivers/gpu/drm/mediatek/mtk_dsi.c ++++ b/drivers/gpu/drm/mediatek/mtk_dsi.c +@@ -6,6 +6,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -347,6 +348,7 @@ + { + mtk_dsi_mask(dsi, DSI_PHY_LCCON, LC_ULPM_EN, 0); + mtk_dsi_mask(dsi, DSI_PHY_LCCON, LC_WAKEUP_EN, LC_WAKEUP_EN); ++ usleep_range(1000, 1200); + mtk_dsi_mask(dsi, DSI_PHY_LCCON, LC_WAKEUP_EN, 0); + } + +@@ -360,6 +362,7 @@ + { + mtk_dsi_mask(dsi, DSI_PHY_LD0CON, LD0_ULPM_EN, 0); + mtk_dsi_mask(dsi, DSI_PHY_LD0CON, LD0_WAKEUP_EN, LD0_WAKEUP_EN); ++ usleep_range(1000, 1200); + mtk_dsi_mask(dsi, DSI_PHY_LD0CON, LD0_WAKEUP_EN, 0); + } + +@@ -838,7 +841,6 @@ + mtk_dsi_config_vdo_timing(dsi); + mtk_dsi_set_interrupt_enable(dsi); + mtk_dsi_lane_ready(dsi); +- mtk_dsi_clk_hs_mode(dsi, 1); + writel(0, dsi->regs + DSI_INTSTA); + enable_irq(dsi->irq); + +@@ -869,7 +871,8 @@ + */ + mtk_dsi_stop(dsi); + +- mtk_dsi_switch_to_cmd_mode(dsi, VM_DONE_INT_FLAG, 500); ++ if ((readl(dsi->regs + DSI_MODE_CTRL) & MODE) != CMD_MODE) ++ mtk_dsi_switch_to_cmd_mode(dsi, VM_DONE_INT_FLAG, 500); + mtk_dsi_reset_engine(dsi); + mtk_dsi_lane0_ulp_mode_enter(dsi); + mtk_dsi_clk_ulp_mode_enter(dsi); +@@ -892,6 +895,10 @@ + if (dsi->enabled) + return; + ++ if (!mtk_dsi_clk_hs_state(dsi)) { ++ mtk_dsi_clk_hs_mode(dsi, 1); ++ usleep_range(200, 300); ++ } + mtk_dsi_set_mode(dsi); + mtk_dsi_start(dsi); + +@@ -957,7 +964,8 @@ + drm_err(drm, "failed to power on dsi\n"); + + mtk_dsi_lane_ready(dsi); +- mtk_dsi_clk_hs_mode(dsi, 1); ++ if (!(dsi->mode_flags & MIPI_DSI_MODE_LPM)) ++ mtk_dsi_clk_hs_mode(dsi, 1); + } + + static void mtk_dsi_bridge_atomic_post_disable(struct drm_bridge *bridge, +@@ -1210,15 +1218,32 @@ + static ssize_t mtk_dsi_host_send_cmd(struct mtk_dsi *dsi, + const struct mipi_dsi_msg *msg, u8 flag) + { ++ bool restore_hs_clk = false; ++ ssize_t ret = 0; ++ ++ if ((msg->flags & MIPI_DSI_MSG_USE_LPM) && mtk_dsi_clk_hs_state(dsi)) { ++ mtk_dsi_clk_hs_mode(dsi, false); ++ usleep_range(200, 300); ++ restore_hs_clk = true; ++ } else if (!(msg->flags & MIPI_DSI_MSG_USE_LPM) && !mtk_dsi_clk_hs_state(dsi)) { ++ mtk_dsi_clk_hs_mode(dsi, true); ++ usleep_range(200, 300); ++ } ++ + mtk_dsi_wait_for_idle(dsi); + mtk_dsi_irq_data_clear(dsi, flag); + mtk_dsi_cmdq(dsi, msg); + mtk_dsi_start(dsi); + + if (!mtk_dsi_wait_for_irq_done(dsi, flag, 2000)) +- return -ETIME; +- else +- return 0; ++ ret = -ETIME; ++ ++ if (restore_hs_clk) { ++ usleep_range(200, 300); ++ mtk_dsi_clk_hs_mode(dsi, true); ++ } ++ ++ return ret; + } + + static ssize_t mtk_dsi_host_transfer(struct mipi_dsi_host *host, +@@ -1284,7 +1309,7 @@ + recv_cnt, *((u8 *)(msg->tx_buf))); + + restore_dsi_mode: +- if (dsi_mode & MODE) { ++ if ((dsi_mode & MODE) && dsi->enabled) { + mtk_dsi_set_mode(dsi); + mtk_dsi_start(dsi); + } +diff --git a/drivers/gpu/drm/panel/panel-novatek-nt36672e.c b/drivers/gpu/drm/panel/panel-novatek-nt36672e.c +--- a/drivers/gpu/drm/panel/panel-novatek-nt36672e.c ++++ b/drivers/gpu/drm/panel/panel-novatek-nt36672e.c +@@ -790,6 +790,194 @@ + * survives this module: on the loader's first frame it is awake, and nothing is + * sent. + */ ++static void ssd2092_gemini_1080x2160_init(struct mipi_dsi_multi_context *ctx) ++{ ++ mipi_dsi_dcs_set_display_off_multi(ctx); ++ mipi_dsi_dcs_enter_sleep_mode_multi(ctx); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb5, 0x00, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x03, 0x96 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb4, 0x21, 0xff }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xe1, 0x00, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xe1, 0x03, 0x00, 0x10 }, 4); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x04, 0x01 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x07, 0x14 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc6, 0x04, 0x2d }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x0e, 0x44 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc1, 0x0c, 0x26 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc1, 0x08, 0x99 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x23, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc2, 0x04, 0x0f }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x11, 0x22 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x12, 0x22 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x13, 0x22 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x19, 0x0b }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x3d, 0xc8 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x0f, 0x20 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0x36, 0x02 }, 2); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc7, 0x01, 0x09 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x15, 0x80 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x1e, 0x02 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x14, 0xc0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x16, 0x50 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x1c, 0xe4 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x28, 0x09 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x24, 0x19 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x12, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x13, 0x14 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x1a, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x1b, 0x14 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc1, 0x0d, 0x87 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc1, 0x0e, 0x87 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc3, 0x00, 0x10, 0x2e, 0x3e, 0x48, 0x5e, 0x6b, 0x7a, 0x83, 0x97, 0xa3, 0xa8, 0xa5, 0xac, 0xad, 0xb5, 0xc1, 0xc4, 0x4e, 0x4f, 0x59, 0x5a }, 23); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc3, 0x15, 0x10, 0x2e, 0x3e, 0x48, 0x5e, 0x6b, 0x7a, 0x83, 0x97, 0xa3, 0xa8, 0xa5, 0xac, 0xad, 0xb5, 0xc1, 0xc4, 0x4e, 0x4f, 0x59, 0x5a }, 23); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x01, 0x8a }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x02, 0x23 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x03, 0xbc }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x04, 0xc0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x05, 0x19 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x06, 0x37 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x07, 0xee }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x08, 0xdd }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x09, 0xcc }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x0a, 0x36 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x0b, 0x70 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x0c, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x0d, 0x8a }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x0e, 0x23 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x0f, 0xbc }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x10, 0xc0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x11, 0x18 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x12, 0xa7 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x13, 0xee }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x14, 0xdd }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x15, 0xcc }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x16, 0x36 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x17, 0x70 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x18, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x31, 0x01 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x00, 0xf0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x01, 0xf0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x02, 0xf0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x03, 0xf0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x1a, 0x02 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x1b, 0x24 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x1d, 0x01 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x1e, 0x01 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x21, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x1f, 0x79 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x20, 0x14 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x22, 0x89 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x23, 0x13 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x24, 0x35 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x26, 0x01 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x27, 0x01 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x2a, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x28, 0x79 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x29, 0x14 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x2b, 0x89 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x2c, 0x33 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x2d, 0x33 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x2e, 0x11 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x2f, 0x11 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x31, 0x22 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x32, 0x01 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x33, 0x04 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x34, 0x11 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x35, 0x11 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x37, 0x22 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x38, 0x01 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x39, 0x04 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x3a, 0x1e }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x3b, 0x1e }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x3c, 0x1e }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x3d, 0x1e }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x40, 0xaa }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x42, 0x1e }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x43, 0x1e }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x44, 0x1e }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x45, 0x1e }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x48, 0xaa }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x02, 0x05 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x03, 0x01 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbc, 0x1e, 0x71 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbc, 0x24, 0x83 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb8, 0x03, 0xa9 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x15, 0x41 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x19, 0x8a }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x1a, 0x32 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x1b, 0xbc }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x1c, 0xc2 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x1d, 0x39 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x1e, 0x37 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x1f, 0xee }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x20, 0xdd }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x21, 0xcc }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x22, 0x36 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x23, 0x70 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x24, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x25, 0x8a }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x26, 0x32 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x27, 0xbc }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x28, 0xc2 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x29, 0x38 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x2a, 0xa7 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x2b, 0xee }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x2c, 0xdd }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x2d, 0xcc }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x2e, 0x36 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x2f, 0x70 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbb, 0x30, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb8, 0x15, 0xa2 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x39, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc6, 0x00, 0x03, 0x40 }, 4); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x18, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x17, 0x28 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x23, 0x15 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x06, 0x2c }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x17, 0x28 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x23, 0x15 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x16, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x28, 0x02, 0x02 }, 4); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x0f, 0x8c }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x10, 0x0c }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x11, 0x23 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x12, 0x9d, 0x9d, 0x9d }, 5); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x25, 0x22 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x0d, 0x40, 0x02 }, 4); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x2f, 0x8c }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc2, 0x04, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc2, 0x05, 0xc0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 11); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x15, 0x33 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x00, 0x5f, 0x5f, 0x61, 0x0a }, 6); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x08, 0x07 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x09, 0x07 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbc, 0x03, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbc, 0x04, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbc, 0x05, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbc, 0x07, 0x10 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbc, 0x08, 0x10 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbc, 0x09, 0x10 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x11, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x12, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x13, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x1d, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x1e, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x1f, 0x00 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc2, 0x00, 0x07 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc1, 0x0b, 0x1f }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb1, 0x05, 0x2f }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0x35, 0x00 }, 2); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb0, 0x01, 0x08, 0x70 }, 4); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb9, 0x25, 0xa0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xba, 0x2f, 0xcc }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xc1, 0x02, 0xb0 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x1c, 0xc4 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xb3, 0x1d, 0x80 }, 3); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0xbd, 0x11, 0x02, 0x22 }, 4); ++ nt36672e_gemini_write_cmd(ctx, (const u8[]){ 0x36, 0x09 }, 2); ++} ++ + static bool gemini_prop_has_ssd2092(const void *prop, int len) + { + int i; +@@ -840,6 +1028,8 @@ + if (ctx->awake) + return 0; + dsi->mode_flags |= MIPI_DSI_MODE_LPM; ++ if (ctx->desc->init_sequence) ++ ctx->desc->init_sequence(&mctx); + mipi_dsi_dcs_exit_sleep_mode_multi(&mctx); + mipi_dsi_msleep(&mctx, ctx->desc->exit_sleep_delay_ms); + mipi_dsi_dcs_set_display_on_multi(&mctx); +@@ -1028,6 +1218,7 @@ + .format = MIPI_DSI_FMT_RGB888, + .lanes = 4, + .panel_name = "Gemini SSD2092 1080x2160 panel", ++ .init_sequence = ssd2092_gemini_1080x2160_init, + .can_adopt = true, + .no_dcs_read = true, + .power_on_delay_ms = 20, +@@ -1037,7 +1228,7 @@ + .display_off_delay_ms = 50, + .sleep_in_delay_ms = 120, + .exit_sleep_delay_ms = 120, +- .display_on_delay_ms = 20, ++ .display_on_delay_ms = 50, + }; + + static int nt36672e_panel_get_modes(struct drm_panel *panel, struct drm_connector *connector) +diff --git a/drivers/input/touchscreen/novatek-nt36xxx.c b/drivers/input/touchscreen/novatek-nt36xxx.c +--- a/drivers/input/touchscreen/novatek-nt36xxx.c ++++ b/drivers/input/touchscreen/novatek-nt36xxx.c +@@ -28,11 +28,13 @@ + #include + #include + #include ++#include + + #include + + #define NVT36XXX_HW_ADDR 0x62 + #define SSD2092_I2C_ADDR 0x53 ++#define SSD2092_DS_CUP_CONTROL 0x0002 + #define SSD2092_X_MAX 1080 + #define SSD2092_Y_MAX 2160 + #define NVT36XXX_FW_ADDR 0x01 +@@ -75,7 +77,11 @@ + u32 orig_irq_type; + u8 fw_version; + u16 pid; ++ u16 last_fw_touch; ++ u16 last_fw_disp; + bool is_ssd2092; ++ bool irq_disabled; ++ struct delayed_work resume_work; + }; + + static int nvt36xxx_write(struct nvt36xxx_data *data, u16 target, +@@ -562,6 +568,9 @@ + int ret = -EIO; + int i; + ++ data->last_fw_touch = 0; ++ data->last_fw_disp = 0; ++ + for (i = 0; i < 6; i++) { + ret = ssd2092_write_u16(data->ssl, 0x0050, 0x0000); + if (!ret) +@@ -580,6 +589,8 @@ + if (!ssd2092_read(data->ssl, 0x0057, buf, sizeof(buf))) + y_nodes = get_unaligned_le16(buf); + ++ data->last_fw_touch = fw_touch; ++ data->last_fw_disp = fw_disp; + data->raw_x_max = SSD2092_X_MAX; + data->raw_y_max = SSD2092_Y_MAX; + dev_info(dev, "SSD2092 FW touch=%#06x disp=%#06x nodes=%ux%u\n", +@@ -724,6 +735,68 @@ + irq_set_irq_type(data->client->irq, data->orig_irq_type); + } + ++/* ++ * Vendor lpm_end2 sequence: wake the SSD2092 TDDI DS16 MCU via ++ * DS_CUP_CONTROL (0x0002) twice without toggling shared GPIO68 reset, which ++ * would blank the active display pipeline. ++ */ ++static int ssd2092_lpm_wake(struct nvt36xxx_data *data) ++{ ++ int ret; ++ ++ ret = ssd2092_write_u16(data->ssl, SSD2092_DS_CUP_CONTROL, 0x0000); ++ if (ret) ++ return ret; ++ usleep_range(1000, 1500); ++ ret = ssd2092_write_u16(data->ssl, SSD2092_DS_CUP_CONTROL, 0x0000); ++ if (ret) ++ return ret; ++ msleep(5); ++ ++ ret = ssd2092_hw_init(data); ++ if (ret) ++ return ret; ++ if (!data->last_fw_touch && !data->last_fw_disp) ++ return -EIO; ++ return 0; ++} ++ ++static void ssd2092_resume_work_fn(struct work_struct *work) ++{ ++ struct nvt36xxx_data *data = ++ container_of(work, struct nvt36xxx_data, resume_work.work); ++ struct device *dev = &data->client->dev; ++ int ret = -EIO; ++ int attempt; ++ ++ if (!data->vcc_reg) ++ ssd2092_enable_pmic_vldo28(); ++ ++ for (attempt = 0; attempt < 5; attempt++) { ++ ret = ssd2092_lpm_wake(data); ++ if (!ret) ++ break; ++ msleep(20); ++ } ++ if (ret) { ++ ret = ssd2092_boot_seeprom(data); ++ if (!ret) ++ ret = ssd2092_hw_init(data); ++ if (ret) ++ dev_warn(dev, "SSD2092 resume init failed: %d\n", ret); ++ } ++ ++ if (data->irq_disabled) { ++ data->irq_disabled = false; ++ enable_irq(data->client->irq); ++ } ++} ++ ++static void ssd2092_cancel_resume_work(void *arg) ++{ ++ cancel_delayed_work_sync(arg); ++} ++ + static int ssd2092_probe(struct i2c_client *client, struct nvt36xxx_data *data) + { + struct device *dev = &client->dev; +@@ -747,6 +820,7 @@ + data->orig_irq_type = dt_trig; + + data->is_ssd2092 = true; ++ INIT_DELAYED_WORK(&data->resume_work, ssd2092_resume_work_fn); + ret = ssd2092_setup_power_and_reset(data); + if (ret) + return ret; +@@ -810,6 +884,11 @@ + if (ret) + return dev_err_probe(dev, ret, "failed to request SSD2092 IRQ\n"); + ++ ret = devm_add_action_or_reset(dev, ssd2092_cancel_resume_work, ++ &data->resume_work); ++ if (ret) ++ return ret; ++ + return 0; + } + +@@ -908,19 +987,44 @@ + return 0; + } + +-static int nvt36xxx_suspend(struct device *dev) ++static int __maybe_unused nvt36xxx_pm_prepare(struct device *dev) + { + struct nvt36xxx_data *data = dev_get_drvdata(dev); + +- disable_irq(data->client->irq); +- +- /* A finger down at suspend would otherwise stay down until it lifts */ +- if (data->is_ssd2092) { +- memset(data->slots, 0, sizeof(data->slots)); +- ssd2092_report_slots(data); ++ if (!data->is_ssd2092) + return 0; ++ ++ cancel_delayed_work_sync(&data->resume_work); ++ if (!data->irq_disabled) { ++ disable_irq(data->client->irq); ++ data->irq_disabled = true; + } ++ memset(data->slots, 0, sizeof(data->slots)); ++ ssd2092_report_slots(data); ++ return 0; ++} + ++static void __maybe_unused nvt36xxx_pm_complete(struct device *dev) ++{ ++ struct nvt36xxx_data *data = dev_get_drvdata(dev); ++ ++ if (!data->is_ssd2092) ++ return; ++ ++ schedule_delayed_work(&data->resume_work, msecs_to_jiffies(60)); ++} ++ ++static int __maybe_unused nvt36xxx_suspend(struct device *dev) ++{ ++ struct nvt36xxx_data *data = dev_get_drvdata(dev); ++ ++ /* SSD2092 TDDI touch quiesces in .prepare before panel/DSI sleep. */ ++ if (data->is_ssd2092) ++ return 0; ++ ++ disable_irq(data->client->irq); ++ ++ /* A finger down at suspend would otherwise stay down until it lifts */ + input_mt_sync_frame(data->input); + input_report_key(data->input, BTN_TOUCH, 0); + input_sync(data->input); +@@ -928,30 +1032,24 @@ + return 0; + } + +-static int nvt36xxx_resume(struct device *dev) ++static int __maybe_unused nvt36xxx_resume(struct device *dev) + { + struct nvt36xxx_data *data = dev_get_drvdata(dev); + +- if (data->is_ssd2092) { +- int ret; +- +- if (!data->vcc_reg) +- ssd2092_enable_pmic_vldo28(); +- ssd2092_reset_pulse(data); +- ret = ssd2092_boot_seeprom(data); +- if (!ret) +- ret = ssd2092_hw_init(data); +- if (ret) +- dev_warn(dev, "SSD2092 resume init failed: %d\n", ret); +- } ++ /* Defer SSD2092 touch wake until .complete after display/DSI is up. */ ++ if (data->is_ssd2092) ++ return 0; + + enable_irq(data->client->irq); + + return 0; + } + +-static DEFINE_SIMPLE_DEV_PM_OPS(nvt36xxx_pm_ops, nvt36xxx_suspend, +- nvt36xxx_resume); ++static const struct dev_pm_ops nvt36xxx_pm_ops = { ++ .prepare = pm_sleep_ptr(nvt36xxx_pm_prepare), ++ .complete = pm_sleep_ptr(nvt36xxx_pm_complete), ++ SYSTEM_SLEEP_PM_OPS(nvt36xxx_suspend, nvt36xxx_resume) ++}; + + static const struct of_device_id nvt36xxx_of_match[] = { + { .compatible = "novatek,nt36772-ts" }, +diff --git a/drivers/leds/rgb/leds-aw9120.c b/drivers/leds/rgb/leds-aw9120.c +--- a/drivers/leds/rgb/leds-aw9120.c ++++ b/drivers/leds/rgb/leds-aw9120.c +@@ -16,6 +16,7 @@ + #include + #include + #include ++#include + #include + #include + +@@ -54,6 +55,7 @@ + /* Channels with a non-zero PWM; the chip's oscillator runs only with one */ + u32 lit; + u32 used; ++ bool powered_down; + u16 imax[AW9120_NUM_IMAX]; + }; + +@@ -278,6 +280,7 @@ + return -ENOMEM; + + chip->dev = dev; ++ i2c_set_clientdata(client, chip); + + ret = devm_mutex_init(dev, &chip->lock); + if (ret) +@@ -345,6 +348,36 @@ + }; + MODULE_DEVICE_TABLE(of, aw9120_of_match); + ++static int __maybe_unused aw9120_suspend(struct device *dev) ++{ ++ struct aw9120 *chip = dev_get_drvdata(dev); ++ ++ guard(mutex)(&chip->lock); ++ if (!chip->lit) { ++ gpiod_set_value_cansleep(chip->enable, 0); ++ chip->powered_down = true; ++ } ++ return 0; ++} ++ ++static int __maybe_unused aw9120_resume(struct device *dev) ++{ ++ struct aw9120 *chip = dev_get_drvdata(dev); ++ int ret = 0; ++ ++ guard(mutex)(&chip->lock); ++ if (chip->powered_down) { ++ gpiod_set_value_cansleep(chip->enable, 1); ++ fsleep(AW9120_POWER_ON_US); ++ ret = aw9120_setup_outputs(chip); ++ if (!ret) ++ chip->powered_down = false; ++ } ++ return ret; ++} ++ ++static DEFINE_SIMPLE_DEV_PM_OPS(aw9120_pm_ops, aw9120_suspend, aw9120_resume); ++ + static const struct i2c_device_id aw9120_id[] = { + { "aw9120" }, + { } +@@ -355,6 +388,7 @@ + .driver = { + .name = "leds-aw9120", + .of_match_table = aw9120_of_match, ++ .pm = pm_sleep_ptr(&aw9120_pm_ops), + }, + .probe = aw9120_probe, + .id_table = aw9120_id, +diff --git a/drivers/power/supply/mt6351-fuel-gauge.c b/drivers/power/supply/mt6351-fuel-gauge.c +--- a/drivers/power/supply/mt6351-fuel-gauge.c ++++ b/drivers/power/supply/mt6351-fuel-gauge.c +@@ -691,9 +691,11 @@ + static void mt6351_fg_report(struct mt6351_fg *fg, s64 uah, int *capacity, int *charge_uah) + { + s64 full = mt6351_fg_rep_full(fg); ++ s64 empty = div_s64(fg->full_uah * fg->empty_pct, 100); ++ s64 span = max_t(s64, full - empty, 1); + +- uah = clamp_t(s64, uah - div_s64(fg->full_uah * fg->empty_pct, 100), 0, full); +- *capacity = div64_s64(uah * 100 + full / 2, full); ++ uah = clamp_t(s64, uah - empty, 0, span); ++ *capacity = div64_s64(uah * 100 + span / 2, span); + *charge_uah = uah; + } + +@@ -997,10 +999,10 @@ + * After a charge, surface charge raises it a few points, which the next rest + * or charge corrects. Called once at probe. + */ +-static void mt6351_fg_pwron_anchor(struct mt6351_fg *fg) ++static void mt6351_fg_pwron_anchor(struct mt6351_fg *fg, int init_ua) + { + unsigned int val; +- int uv, mc, pct; ++ int uv, mc, pct, live_uv; + + if (regmap_read(fg->regmap, MT6351_AUXADC_ADC21, &val) || + !(val & MT6351_PWRON_RDY) || thermal_zone_get_temp(fg->tz, &mc)) +@@ -1014,6 +1016,23 @@ + if (pct < 0) + return; + ++ /* ++ * ADC21 is only latched on cold battery attach and goes stale across ++ * warm reboots or USB reflashes while VBAT remains present. ++ */ ++ if (!mt6351_fg_voltage(fg, &live_uv)) { ++ int live_ocv = mt6351_fg_ocv(fg, live_uv, init_ua, mc); ++ int live_pct = power_supply_batinfo_ocv2cap(fg->info, live_ocv, mc / 1000); ++ ++ if (abs(uv - live_ocv) > 80000 || ++ (live_pct >= 0 && abs(pct - live_pct) > 10)) { ++ dev_info(fg->dev, ++ "ignoring stale start-up OCV %d uV (%d %%) vs live %d uV (%d %%)\n", ++ uv, pct, live_ocv, live_pct); ++ return; ++ } ++ } ++ + guard(mutex)(&fg->lock); + fg->anchor_uah = div_s64(fg->full_uah * clamp(pct, 0, 100), 100); + fg->anchor_car = fg->car; +@@ -1103,8 +1122,12 @@ + WRITE_ONCE(fg->info, info); + + /* Open the first current window now, so the current is known 5 s on. */ +- mt6351_fg_read(fg, &ret, &ret); +- mt6351_fg_pwron_anchor(fg); ++ { ++ int init_ua = 0, init_uah = 0; ++ ++ ret = mt6351_fg_read(fg, &init_ua, &init_uah); ++ mt6351_fg_pwron_anchor(fg, ret ? 0 : init_ua); ++ } + + /* + * A charger attached while the system sleeps wakes it, so that the +@@ -1153,8 +1176,12 @@ + if (!READ_ONCE(fg->info)) + return -ENODATA; + +- scoped_guard(mutex, &fg->lock) ++ scoped_guard(mutex, &fg->lock) { + fg->r25_uohm = r; ++ fg->empty_valid = false; ++ if (!fg->anchor_trusted) ++ fg->anchored = false; ++ } + power_supply_changed(fg->psy); + + return count; +diff --git a/drivers/soc/mediatek/mt6797-ccci-cldma.c b/drivers/soc/mediatek/mt6797-ccci-cldma.c +--- a/drivers/soc/mediatek/mt6797-ccci-cldma.c ++++ b/drivers/soc/mediatek/mt6797-ccci-cldma.c +@@ -1310,6 +1310,9 @@ + mt6797_ccci_free_irqs(cdev); + cancel_work_sync(&cdev->rx_work); + mt6797_ccci_free_rings(cdev); ++ if (cdev->infracfg) ++ regmap_update_bits(cdev->infracfg, INFRA_AO_MD_SRCCLKENA, ++ 0xff, 0x00); + cdev->md_state = MT6797_MD_STATE_GATED; + cdev->active_stage = 0; + stage = 0; +@@ -1473,6 +1476,9 @@ + mutex_lock(&cdev->state_lock); + mt6797_ccci_apply_stage(cdev, clamp_t(u32, stage, 0, 3)); + mutex_unlock(&cdev->state_lock); ++ } else if (cdev->infracfg) { ++ regmap_update_bits(cdev->infracfg, INFRA_AO_MD_SRCCLKENA, ++ 0xff, 0x00); + } + + dev_info(&pdev->dev, +diff --git a/drivers/soc/mediatek/mt6797-spm-sleep.c b/drivers/soc/mediatek/mt6797-spm-sleep.c +--- a/drivers/soc/mediatek/mt6797-spm-sleep.c ++++ b/drivers/soc/mediatek/mt6797-spm-sleep.c +@@ -482,11 +482,11 @@ + u32 im_resident; /* the program IM holds after a return, or 0 */ + } s; + +-static unsigned int timer_sec = 30; ++static unsigned int timer_sec = 600; + module_param(timer_sec, uint, 0644); + MODULE_PARM_DESC(timer_sec, "PCM wake timer in seconds (1-600)"); + +-static bool pmic_modes; ++static bool pmic_modes = true; + module_param(pmic_modes, bool, 0644); + MODULE_PARM_DESC(pmic_modes, "Set the static PMIC sleep modes for each suspend"); + +@@ -1388,7 +1388,11 @@ + disable_irq_wake(s.irq); + disable_irq(s.irq); + spm_pmic_finish(); +- spm_log_wake("wake"); ++ if (!s.entered || !s.wake.returned || s.wake.backstop || ++ s.wake.r12 != BIT(0)) ++ spm_log_wake("wake"); ++ else ++ dev_dbg(&s.pdev->dev, "suspend timer tick r12=%08x\n", s.wake.r12); + } + + static void spm_log_wake(const char *what) +@@ -1609,7 +1613,7 @@ + MODULE_PARM_DESC(sodi_idle_max_ms, "SODI idle: longest period in ms (1-2000)"); + + /* Whether to register the cpuidle driver at all (stage D5d bisects it) */ +-static bool sodi_idle = true; ++static bool sodi_idle; + module_param(sodi_idle, bool, 0444); + MODULE_PARM_DESC(sodi_idle, "SODI idle: register the CPU0 cpuidle driver"); + +@@ -1870,11 +1874,22 @@ + s.idle_registered = false; + } + ++static bool spm_suspend_again(void) ++{ ++ if (!s.entered || !s.wake.returned || s.wake.backstop) ++ return false; ++ if (pm_wakeup_pending()) ++ return false; ++ /* Stay asleep across silent PCM timer rollovers; wake on EINT/other. */ ++ return s.wake.r12 == BIT(0); ++} ++ + static const struct platform_suspend_ops spm_suspend_ops = { + .valid = spm_valid, + .prepare = spm_prepare, + .enter = spm_enter, + .finish = spm_finish, ++ .suspend_again = spm_suspend_again, + }; + + /* ---- load ---- */ diff --git a/patches/kernel/0009-mt6797-wlan-drop-free-stability.patch b/patches/kernel/0009-mt6797-wlan-drop-free-stability.patch new file mode 100644 index 0000000..ac28914 --- /dev/null +++ b/patches/kernel/0009-mt6797-wlan-drop-free-stability.patch @@ -0,0 +1,692 @@ +--- a/drivers/net/wireless/mediatek/mt6797/mac-priv.h ++++ b/drivers/net/wireless/mediatek/mt6797/mac-priv.h +@@ -51,6 +51,7 @@ + * several requests. + */ + #define MT6797_SCAN_REQUEST_CHANNELS 32U ++#define MT6797_ONLINE_SCAN_CHANNELS 4U + #define MT6797_SCAN_SSIDS 4U + + struct mt6797_scan_frame { +@@ -433,11 +434,9 @@ + + #define MT6797_JOIN_TX_HDRLEN(fc) ((fc) & MT6797_JOIN_TX_QOS_BIT ? 26U : 24U) + +-#define MT6797_JOIN_DATA_TX_FAILURES 8U +-/* At low signal eight frames can fail on a link that still works, and they take +- * under two seconds at low traffic, so they must also span this long. +- */ +-#define MT6797_JOIN_DATA_TX_FAILURE_NS (3ULL * NSEC_PER_SEC) ++#define MT6797_JOIN_DATA_TX_FAILURES 16U ++/* Allow brief interference bursts without falsely tearing down the link. */ ++#define MT6797_JOIN_DATA_TX_FAILURE_NS (5ULL * NSEC_PER_SEC) + /* One frame carries one rate here, so a failed probe of another rate loses that + * frame, and at low traffic minstrel_ht makes most frames probes. At most one + * in this many may be one. +@@ -691,6 +690,10 @@ + unsigned int scan_packets; + /* A scan while connected: the worker submits it and reads its events. */ + bool scan_online, scan_online_ready, scan_online_cancel; ++ u64 scan_online_end_ns; ++ u64 last_ap_activity_ns, last_beacon_timeout_ns; ++ unsigned int beacon_timeout_streak, ccmp_live_keys; ++ bool gtk_rekey_pending; + /* Signal threshold, from the access point's frames (1/16 dB average). */ + int cqm_thold, cqm_last, cqm_average; + unsigned int cqm_hyst, cqm_samples, cqm_beacons; +@@ -728,7 +731,7 @@ + * transmit fell to 0.5-9.5 Mbit/s on channel 40. + */ + #define MT6797_TX_ATTEMPTS 30U +-#define MT6797_TX_ATTEMPTS_DATA 3U ++#define MT6797_TX_ATTEMPTS_DATA 7U + + /* A current, owned monitor notification is a normal connection loss, not a + * malformed transport event. End traffic and queue standard core teardown; +@@ -742,7 +745,7 @@ + * (strictly checked PTK/GTK admissions only), so it ignores no more than the + * vendor would. A dead link stops that clock, and its next event is a loss. + */ +-#define MT6797_CCMP_TIMEOUT_FRESH_RX_MS 2000 ++#define MT6797_CCMP_TIMEOUT_FRESH_RX_MS 6000 + + #define MT6797_CCMP_TIMEOUT_IGNORE_NAMED 16 + +@@ -839,9 +842,6 @@ + const unsigned char ap[6], unsigned char bmc_index, + unsigned int *reason_out); + +-bool mt6797_ccmp_rx_eapol_rekey(const unsigned char *packet, size_t bytes, +- const struct mt6797_ccmp_rx_context *context); +- + int mt6797_mac_join_open_lifetime(struct mt6797_mac *mac); + void mt6797_mac_join_read_bss(struct mt6797_mac *mac, struct ieee80211_vif *vif, + const struct ieee80211_bss_conf *info); +--- a/drivers/net/wireless/mediatek/mt6797/mcu.h ++++ b/drivers/net/wireless/mediatek/mt6797/mcu.h +@@ -868,7 +868,7 @@ + (status_report ? (!pid || pid > 127) : pid != 0) || + !lifetime_ms || lifetime_ms > 10000 || !attempt_count || attempt_count > 30) + return false; +- if ((frame[6] & 1) || (frame[12] == 0x88 && frame[13] == 0x8e)) ++ if (frame[6] & 1) + return false; + lifetime = (lifetime_ms * 1000U / 1024U) >> 5; + if (!lifetime) +--- a/drivers/net/wireless/mediatek/mt6797/data.c ++++ b/drivers/net/wireless/mediatek/mt6797/data.c +@@ -807,10 +807,9 @@ + source_any |= ethernet[6 + i] != 0; + pn[i] = packet[32 + 5 - i]; + } +- /* Ethernet-II only; EAPOL remains on the existing control-port path. */ ++ /* Ethernet-II (including PTK-encrypted EAPOL-Key GTK handshakes). */ + if (!source_any || (ethernet[6] & 1) || +- (((unsigned int)ethernet[12] << 8) | ethernet[13]) < 0x0600 || +- (ethernet[12] == 0x88 && ethernet[13] == 0x8e)) ++ (((unsigned int)ethernet[12] << 8) | ethernet[13]) < 0x0600) + return false; + tid = packet[9] & 15; + last = tid ? context->tid_pn[tid - 1] : context->pn; +@@ -1390,6 +1389,8 @@ + if (mac->ccmp_queued < MT6797_CCMP_DIAG_CHECKED_MAX) + mac->ccmp_queued++; + mac->ccmp_last_checked_rx = ktime_get_ns(); ++ mac->last_ap_activity_ns = mac->ccmp_last_checked_rx; ++ mac->beacon_timeout_streak = 0; + __skb_queue_tail(received, skb); + return 0; + } +@@ -1756,7 +1757,7 @@ + + bool mt6797_ccmp_owned_loss(struct mt6797_mac *mac, size_t bytes) + { +- u64 now; ++ u64 now, fresh; + + if (!mt6797_join_event(mac->join_packet, bytes, 0x13, 4) || + mac->join_packet[5] || mac->join_packet[8] || !mt6797_ccmp_rx_ready(mac) || +@@ -1766,21 +1767,36 @@ + mac->join_key_pairwise != 1 || mac->join_key_group != 1 || mac->ccmp_loss_reported) + return false; + now = ktime_get_ns(); +- if (mac->join_packet[9] == 4 && mac->ccmp_queued && +- mac->ccmp_last_checked_rx <= now && +- now - mac->ccmp_last_checked_rx < MT6797_CCMP_TIMEOUT_FRESH_RX_MS * NSEC_PER_MSEC) { +- if (++mac->ccmp_timeout_ignored <= MT6797_CCMP_TIMEOUT_IGNORE_NAMED) ++ if (mac->join_packet[9] == 4) { ++ /* Firmware away on a scan or within post-scan settling window. */ ++ if (mac->scan_online || ++ (mac->scan_online_end_ns && now >= mac->scan_online_end_ns && ++ now - mac->scan_online_end_ns < 5ULL * NSEC_PER_SEC)) ++ return true; ++ fresh = max3(mac->ccmp_last_checked_rx, mac->last_ap_activity_ns, ++ mac->join_data_tx_ok_ns); ++ if (fresh && fresh <= now && ++ now - fresh < (u64)MT6797_CCMP_TIMEOUT_FRESH_RX_MS * NSEC_PER_MSEC) { ++ mac->beacon_timeout_streak = 0; ++ if (++mac->ccmp_timeout_ignored <= MT6797_CCMP_TIMEOUT_IGNORE_NAMED) ++ dev_info(wiphy_dev(mac->hw->wiphy), ++ "one-shot WLAN BSS timeout ignored: reason=4 age_ms=%llu data_ms=%llu ignored=%u\n", ++ (now - fresh) / NSEC_PER_MSEC, ++ now > mac->join_data_started ? ++ (now - mac->join_data_started) / NSEC_PER_MSEC : 0, ++ mac->ccmp_timeout_ignored); ++ return true; ++ } ++ if (mac->last_beacon_timeout_ns && fresh > mac->last_beacon_timeout_ns) ++ mac->beacon_timeout_streak = 0; ++ mac->last_beacon_timeout_ns = now; ++ if (++mac->beacon_timeout_streak < 2) { + dev_info(wiphy_dev(mac->hw->wiphy), +- "one-shot WLAN BSS timeout ignored: reason=4 checked_rx_age_ms=%llu data_ms=%llu ignored=%u\n", +- (now - mac->ccmp_last_checked_rx) / NSEC_PER_MSEC, +- now > mac->join_data_started ? +- (now - mac->join_data_started) / NSEC_PER_MSEC : 0, +- mac->ccmp_timeout_ignored); +- return true; +- } +- /* The firmware away on a scan: its notice is not a lost connection. */ +- if (mac->join_packet[9] == 4 && mac->scan_online) +- return true; ++ "one-shot WLAN BSS timeout deferred: reason=4 streak=%u\n", ++ mac->beacon_timeout_streak); ++ return true; ++ } ++ } + mt6797_mac_join_end_data(mac, "connection-loss"); + mt6797_ccmp_connection_lost(mac, "monitor", mac->join_packet[9]); + return true; +@@ -1843,6 +1859,8 @@ + IEEE80211_SKB_RXCB(skb)->flag |= RX_FLAG_NO_SIGNAL_VAL; + } + mt6797_ccmp_pm_beacon(mac, offset, bytes); ++ mac->last_ap_activity_ns = ktime_get_ns(); ++ mac->beacon_timeout_streak = 0; + __skb_queue_tail(received, skb); + return 0; + } +@@ -1983,71 +2001,3 @@ + return true; + } + +-bool mt6797_ccmp_rx_eapol_rekey(const unsigned char *packet, size_t bytes, +- const struct mt6797_ccmp_rx_context *context) +-{ +- unsigned char pn[6]; +- size_t offset = 48; +- unsigned int groups, fc, i, tid; +- const unsigned char *last; +- const unsigned char *ethernet; +- bool greater = false, own_any = false, ap_any = false, source_any = false; +- +- if (!packet || !context || bytes < 16 || bytes > 2352 || +- !context->authorized || !context->active || !context->seeded || +- !context->pairwise || context->cipher != 0x000fac04U || +- context->key_bytes != 16 || context->key_id || +- context->wlan_index != 1 || context->rxd_bssid > 63 || !context->channel || +- (context->own[0] & 1) || (context->ap[0] & 1)) +- return false; +- for (i = 0; i < 6; i++) { +- own_any |= context->own[i] != 0; +- ap_any |= context->ap[i] != 0; +- } +- if (!own_any || !ap_any || mt6797_join_le16(packet) != bytes || +- (mt6797_join_le16(packet + 2) >> 13) != 2 || +- packet[4] != 0x02 || packet[5] != context->channel || +- (packet[6] & 0xbf) != 0x8e || +- packet[7] != (unsigned int)context->rxd_bssid << 2 || +- packet[8] != context->wlan_index || (packet[9] & 0xf0) != 0x40 || +- !mt6797_ccmp_rx_status_ok(mt6797_join_le16(packet + 10))) +- return false; +- groups = (mt6797_join_le16(packet + 2) >> 9) & 15; +- if ((groups & 9) != 9) +- return false; +- if (groups & 2) +- offset += 8; +- if (groups & 4) +- offset += 24; +- if (packet[6] & 0x40) +- offset += 2; +- if (offset > bytes || bytes - offset <= 14) +- return false; +- fc = mt6797_join_le16(packet + 16); +- if ((fc & ~(0x2800U | MT6797_CCMP_RX_QOS_BIT)) != 0x4208 || +- (mt6797_join_le16(packet + 24) & 15) || +- !mt6797_ccmp_rx_tid_ok(packet, fc, 0x40) || +- mt6797_join_le32(packet + 28)) +- return false; +- ethernet = packet + offset; +- for (i = 0; i < 6; i++) { +- if (packet[18 + i] != context->ap[i] || ethernet[i] != context->own[i]) +- return false; +- source_any |= ethernet[6 + i] != 0; +- pn[i] = packet[32 + 5 - i]; +- } +- if (!source_any || (ethernet[6] & 1) || +- ethernet[12] != 0x88 || ethernet[13] != 0x8e) +- return false; +- tid = packet[9] & 15; +- last = tid ? context->tid_pn[tid - 1] : context->pn; +- for (i = 0; i < 6; i++) { +- if (pn[i] < last[i]) +- return false; +- if (pn[i] > last[i]) { +- greater = true; +- break; +- } +- } +- return greater; +-} +--- a/drivers/net/wireless/mediatek/mt6797/join.c ++++ b/drivers/net/wireless/mediatek/mt6797/join.c +@@ -595,6 +595,12 @@ + mac->ps_failed = false; + mac->ccmp_last_checked_rx = 0; + mac->ccmp_timeout_ignored = 0; ++ mac->scan_online_end_ns = 0; ++ mac->last_ap_activity_ns = 0; ++ mac->last_beacon_timeout_ns = 0; ++ mac->beacon_timeout_streak = 0; ++ mac->ccmp_live_keys = 0; ++ mac->gtk_rekey_pending = false; + reinit_completion(&mac->ccmp_dtim_done); + mac->ccmp_dtim_period = 0; + mac->ccmp_dtim_status = 0; +@@ -913,6 +919,8 @@ + mac->join_data_tx_done++; + mac->join_data_tx_failures_in_row = 0; + mac->join_data_tx_ok_ns = ktime_get_ns(); ++ mac->last_ap_activity_ns = mac->join_data_tx_ok_ns; ++ mac->beacon_timeout_streak = 0; + ieee80211_tx_info_clear_status(IEEE80211_SKB_CB(skb)); + IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_STAT_NOACK_TRANSMITTED; + skb_queue_tail(&mac->credit_retired_queue, skb); +@@ -1218,6 +1226,9 @@ + else if (owned && mac->join_key_done && mac->join_key_group_submitted && + !mac->join_key_done_second) + window = "second after=group"; ++ else if (owned && mac->join_key_done && mac->join_key_done_second && ++ mac->join_data_phase && !mac->join_data_ended) ++ window = "rekey after=group"; + if (!window) { + dev_info(wiphy_dev(mac->hw->wiphy), + "one-shot WLAN join key done refused: bss=%u peer=%u broadcast=%u seq=%u submitted=%u%u recorded=%u%u\n", +@@ -1967,6 +1978,8 @@ + mac->join_data_tx_done++; + mac->join_data_tx_failures_in_row = 0; + mac->join_data_tx_ok_ns = ktime_get_ns(); ++ mac->last_ap_activity_ns = mac->join_data_tx_ok_ns; ++ mac->beacon_timeout_streak = 0; + return; + } + mac->join_data_tx_failed++; +@@ -2055,10 +2068,10 @@ + */ + if (!mac->join_closed && (mac->join_key_pairwise_submitted || + mac->join_key_group_submitted) && +- mac->ccmp_key_disables < 2) { ++ mac->ccmp_live_keys > 0) { + dev_info(wiphy_dev(mac->hw->wiphy), +- "one-shot WLAN join rearm deferred: key_removals=%u\n", +- mac->ccmp_key_disables); ++ "one-shot WLAN join rearm deferred: live_keys=%u\n", ++ mac->ccmp_live_keys); + goto unlock; + } + mac->join_rearm_pending = false; +@@ -2222,9 +2235,6 @@ + ret = mt6797_mac_join_guard(mac, deadline); + if (ret) + goto failed; +- ret = mt6797_mac_online_scan_step(mac); +- if (ret) +- goto failed; + mt6797_native_diag_step(mac); + if (mac->join_data_phase && !mac->join_data_ended && + ktime_get_ns() >= mac->join_data_deadline) +@@ -2237,7 +2247,8 @@ + select_more: + branch = 3; + select = !mac->join_inflight && !mac->join_page_debt; +- if (channel_release_holds_tx) ++ if (channel_release_holds_tx || mac->gtk_rekey_pending || ++ (mac->scan_online && !mac->scan_online_ready)) + select = false; + /* PID-budget exhaustion ends the data phase in the queue path; evaluate it + * before any frame is selected so the step disables and the fence holds. +@@ -2268,9 +2279,11 @@ + u64 now_ns = ktime_get_ns(); + + skb_queue_walk_safe(&mac->join_queue, walk, tmp) { +- bool data = (get_unaligned_le16(walk->data) & 0x0c) == 0x08; ++ u16 walk_fc = get_unaligned_le16(walk->data); ++ bool data = (walk_fc & 0x0c) == 0x08; + bool port = IEEE80211_SKB_CB(walk)->control.flags & + IEEE80211_TX_CTRL_PORT_CTRL_PROTO; ++ bool prekey_eapol = port && !(walk_fc & IEEE80211_FCTL_PROTECTED); + + if (walk == mac->join_internal && + (now_ns < mac->join_hold_until || +@@ -2281,18 +2294,18 @@ + /* Ordinary data goes out only inside the data phase; a + * frame still queued when the phase ended is discarded. + */ +- if (data && !port && walk != mac->join_internal && ++ if (data && !prekey_eapol && walk != mac->join_internal && + mac->join_data_phase && !mac->join_data_ended && + mac->join_next_pid > MT6797_JOIN_DATA_LAST_PID) + mt6797_mac_join_end_data(mac, "pidbudget"); +- if (data && !port && walk != mac->join_internal && ++ if (data && !prekey_eapol && walk != mac->join_internal && + (!mac->join_data_phase || mac->join_data_ended)) { + __skb_unlink(walk, &mac->join_queue); + mac->join_queue_bytes -= walk->len; + __skb_queue_tail(&discard, walk); + continue; + } +- if (data && !port && walk != mac->join_internal) { ++ if (data && !prekey_eapol && walk != mac->join_internal) { + if (!mt6797_ccmp_data_room(mac, walk->len)) + continue; + } else if (mac->data_slots.count) { +@@ -2349,19 +2362,20 @@ + size_t eth_bytes = 14 + skb->len - (hl + 8); + bool port = IEEE80211_SKB_CB(skb)->control.flags & + IEEE80211_TX_CTRL_PORT_CTRL_PROTO; ++ bool prekey_eapol = port && !(fc & IEEE80211_FCTL_PROTECTED); + + if (skb->len < hl + 12 || eth_bytes > MT6797_JOIN_ETH_MAX_BYTES || + !mac->join_sta_active || +- (!port && (!mac->join_data_phase || mac->join_data_ended))) { ++ (!prekey_eapol && (!mac->join_data_phase || mac->join_data_ended))) { + ret = -EINVAL; + goto failed; + } +- ret = mt6797_ccmp_assign_pid(mac, false, !port); ++ ret = mt6797_ccmp_assign_pid(mac, false, !prekey_eapol); + if (ret) + goto failed; + mac->join_last_acked = false; + reinit_completion(&mac->join_frame_done); +- if (!port) { ++ if (!prekey_eapol) { + memcpy(mac->join_eth, skb->data + 16, ETH_ALEN); + memcpy(mac->join_eth + 6, skb->data + 10, ETH_ALEN); + memcpy(mac->join_eth + 12, skb->data + hl + 6, 2); +@@ -2387,6 +2401,8 @@ + (IEEE80211_SKB_CB(skb)->flags & + IEEE80211_TX_CTL_RATE_CTRL_PROBE)) + sample = true; ++ if (port) ++ sample = true; + if (sample) { + mac->tx_sample_counter = 0; + mac->tx_report_ns = ktime_get_ns(); +@@ -2395,7 +2411,8 @@ + eth_bytes, 1, + sample ? mac->join_pid : 0, + sample, +- 500, MT6797_TX_ATTEMPTS_DATA, ++ 500, ++ port ? MT6797_TX_ATTEMPTS : MT6797_TX_ATTEMPTS_DATA, + per_frame, + deadline); + if (ret) +@@ -2468,6 +2485,9 @@ + } + } + } ++ ret = mt6797_mac_online_scan_step(mac); ++ if (ret) ++ goto failed; + mt6797_hif_rx_batch_pass(mac->hif); + mac->join_pass_read = true; + for (n = 0; n < 8; n++) { +@@ -2881,16 +2901,6 @@ + } + continue; + } +- if (admitted && mt6797_ccmp_rx_ready(mac) && +- mt6797_ccmp_rx_eapol_rekey(mac->join_packet, +- rx.logical_bytes, +- &mac->ccmp_rx)) { +- dev_info(wiphy_dev(mac->hw->wiphy), +- "one-shot WLAN peer GTK rekey: triggering reassociation\n"); +- mt6797_mac_join_end_data(mac, "gtk-rekey"); +- mt6797_ccmp_connection_lost(mac, "gtk-rekey", 0); +- continue; +- } + if (admitted) + ret = mt6797_ccmp_queue_rx(mac, rx.logical_bytes, + &received); +--- a/drivers/net/wireless/mediatek/mt6797/main.c ++++ b/drivers/net/wireless/mediatek/mt6797/main.c +@@ -13,8 +13,8 @@ + /* Fast power save by default: with CONFIG_CFG80211_DEFAULT_PS it is on at every + * join, and it took about 57 mA off a quiet link. 0 offers none. + */ +-static uint power_save = 2; +-module_param(power_save, uint, 0444); ++static uint power_save = 0; ++module_param(power_save, uint, 0644); + MODULE_PARM_DESC(power_save, "802.11 power save offered to mac80211: 0 none, 1 maximum, 2 fast"); + module_param(wlan_irq, bool, 0444); + MODULE_PARM_DESC(wlan_irq, "Serve receive from the WLAN interrupt when the device tree gives one"); +@@ -858,9 +858,10 @@ + unsigned int count, next_seq; + int ret; + +- /* A request is all probing or all passive. */ ++ /* Online scans use short 4-channel excursions so traffic is not stalled. */ + count = min((probing ? mac->scan_probing : mac->scan_total) - mac->scan_next, +- MT6797_SCAN_REQUEST_CHANNELS); ++ mac->scan_online ? MT6797_ONLINE_SCAN_CHANNELS : ++ MT6797_SCAN_REQUEST_CHANNELS); + /* Keep scan_sequence monotonic within a session so stale 0x0d events + * emitted after a cancelled scan never match a later scan request. + */ +@@ -894,6 +895,7 @@ + if (!mac->scan_online) + return; + mac->scan_online = false; ++ mac->scan_online_end_ns = ktime_get_ns(); + dev_info(wiphy_dev(mac->hw->wiphy), + "one-shot WLAN connected scan: requests=%u aborted=%u\n", + mac->scan_sequence, aborted); +@@ -911,7 +913,8 @@ + + if (!mac->scan_online && !mac->scan_online_cancel) + return 0; +- if (mac->join_page_debt || mac->join_credit_pending || mac->join_inflight) ++ if (mac->join_page_debt || mac->join_credit_pending || mac->join_inflight || ++ mac->data_slots.count || mac->join_data_page_debt || mac->gtk_rekey_pending) + return 0; + if (mac->scan_online_cancel) { + mac->scan_online_cancel = false; +@@ -1291,9 +1294,10 @@ + /* The firmware's default dwell: it keeps returning to the channel. */ + mac->scan_dwell_ms = 0; + mac->scan_channels = mask; +- mac->scan_deadline = ktime_get_ns() + 5 * NSEC_PER_SEC; ++ mac->scan_deadline = ktime_get_ns() + 15 * NSEC_PER_SEC; + mac->scan_online_ready = true; + mac->scan_online = true; ++ schedule_delayed_work(&mac->join_work, 0); + dev_info(wiphy_dev(hw->wiphy), + "one-shot WLAN connected scan: admitted=1 channels=%u probing=%u ssids=%u sequence=%u\n", + mac->scan_total, mac->scan_probing, mac->scan_n_ssids, mac->sequence); +@@ -1758,8 +1762,8 @@ + * itself still decides with the rendezvous and quiescence rules. + */ + mutex_lock(&mac->mutex); +- if (mac->join_rearm_pending && !mac->join_closed && !mac->first_error && +- !mac->closing) ++ if (mac->join_rearm_pending && !mac->ccmp_live_keys && ++ !mac->join_closed && !mac->first_error && !mac->closing) + schedule_delayed_work(&mac->join_work, msecs_to_jiffies(20)); + mutex_unlock(&mac->mutex); + while ((skb = __skb_dequeue(&discard))) { +@@ -1812,8 +1816,14 @@ + mac->closing, mac->first_error); + return; + } +- if (mac->join_inflight || mac->data_slots.count || mac->join_page_debt) { ++ if (mac->data_slots.count || mac->join_data_page_debt) { ++ ret = -EBUSY; ++ goto out; ++ } ++ if (mac->join_inflight || mac->join_page_debt) { + ret = mt6797_mac_join_wait_management(mac); ++ if (ret == -EPROTO && (mac->data_slots.count || mac->join_data_page_debt)) ++ ret = -EBUSY; + if (ret) + goto out; + } +@@ -1868,14 +1878,33 @@ + + if (cmd == DISABLE_KEY) { + mutex_lock(&mac->mutex); +- if (mac->ccmp_gtk_deferred == key) ++ if (mac->ccmp_gtk_deferred == key) { + mac->ccmp_gtk_deferred = NULL; ++ mutex_unlock(&mac->mutex); ++ return 0; ++ } ++ if (mac->ccmp_live_keys > 0) ++ mac->ccmp_live_keys--; ++ if (!pairwise && mac->join_data_phase && !mac->join_data_ended && ++ mac->ccmp_rx.authorized && mac->ccmp_ptk && ++ !mac->closing && !mac->first_error) { ++ if (mac->ccmp_gtk == key) { ++ mac->ccmp_gtk_rx.active = false; ++ spin_lock_irqsave(&mac->join_queue.lock, flags); ++ mac->ccmp_gtk = NULL; ++ spin_unlock_irqrestore(&mac->join_queue.lock, flags); ++ } ++ mutex_unlock(&mac->mutex); ++ mutex_lock(&mac->ccmp_receive_mutex); ++ mutex_unlock(&mac->ccmp_receive_mutex); ++ dev_info(wiphy_dev(hw->wiphy), ++ "one-shot WLAN GTK key retired in-place: keyidx=%d\n", ++ key->keyidx); ++ return 0; ++ } + mutex_unlock(&mac->mutex); + return mt6797_ccmp_disable_key(mac); + } +- +- if (cmd == DISABLE_KEY) +- return 0; + mutex_lock(&mac->mutex); + if (!mac->ccmp_pm_connected) { + ret = -EOPNOTSUPP; +@@ -1893,6 +1922,117 @@ + "one-shot WLAN join key deferred: group before pairwise\n"); + return 0; + } ++ /* In-place GTK rekey during an established data phase: install the new ++ * group key under MT6797_JOIN_BMC_WLAN_INDEX without tearing down the link. ++ */ ++ if (!pairwise && !sta && vif == mac->vif && mac->join_rsn && ++ mac->join_data_phase && !mac->join_data_ended && ++ mac->ccmp_rx.active && mac->ccmp_rx.authorized && ++ mac->join_key_pairwise == 1 && !mac->ccmp_closed && ++ !mac->closing && !mac->first_error) { ++ u64 wait_end; ++ ++ if (!((key->cipher == WLAN_CIPHER_SUITE_CCMP && key->keylen == 16) || ++ (key->cipher == WLAN_CIPHER_SUITE_TKIP && key->keylen == 32)) || ++ key->keyidx < 0 || key->keyidx > 3) { ++ ret = -EOPNOTSUPP; ++ goto failed; ++ } ++ mutex_unlock(&mac->mutex); ++ mutex_lock(&mac->ccmp_receive_mutex); ++ ieee80211_get_key_rx_seq(key, 0, &seed); ++ for (tid = 1; tid < MT6797_CCMP_RX_TIDS; tid++) ++ ieee80211_get_key_rx_seq(key, tid, &tid_seed[tid - 1]); ++ mutex_unlock(&mac->ccmp_receive_mutex); ++ mutex_lock(&mac->mutex); ++ if (mac->ccmp_closed || mac->first_error || mac->closing || ++ mac->join_retired || !mac->join_data_phase || mac->join_data_ended) { ++ ret = mac->first_error ? mac->first_error : -EOPNOTSUPP; ++ goto failed; ++ } ++ mac->gtk_rekey_pending = true; ++ schedule_delayed_work(&mac->join_work, 0); ++ wait_end = ktime_get_ns() + 1000 * NSEC_PER_MSEC; ++ while ((mac->join_inflight || mac->data_slots.count || ++ mac->join_page_debt || mac->join_data_page_debt || ++ mac->join_credit_pending || !mt6797_hif_normal_idle(mac->hif)) && ++ ktime_get_ns() < wait_end && ++ !mac->first_error && !mac->closing && ++ !mac->join_retired && !mac->join_data_ended) { ++ mutex_unlock(&mac->mutex); ++ usleep_range(2000, 4000); ++ mutex_lock(&mac->mutex); ++ } ++ if (mac->ccmp_closed || mac->first_error || mac->closing || ++ mac->join_retired || !mac->join_data_phase || mac->join_data_ended) { ++ mac->gtk_rekey_pending = false; ++ ret = mac->first_error ? mac->first_error : -ECANCELED; ++ goto failed; ++ } ++ if (mac->join_inflight || mac->data_slots.count || ++ mac->join_page_debt || mac->join_data_page_debt || ++ mac->join_credit_pending || !mt6797_hif_normal_idle(mac->hif)) { ++ mac->gtk_rekey_pending = false; ++ ret = -EBUSY; ++ goto failed; ++ } ++ if (mac->sequence > 200 && mac->sequence_base && ++ !mt6797_hif_recycle_sequences(mac->hif, mac->sequence_base)) ++ mac->sequence = mac->sequence_base; ++ if (mac->sequence > 253) { ++ mac->gtk_rekey_pending = false; ++ ret = -ENOSPC; ++ goto failed; ++ } ++ mac->ccmp_gtk_rx.active = false; ++ mac->join_credit_deadline = ktime_get_ns() + 150 * NSEC_PER_MSEC; ++ reinit_completion(&mac->join_credit_done); ++ mac->join_credit_pending = true; ++ mac->join_page_debt = 1; ++ ret = mt6797_hif_join_key_cipher(mac->hif, mac->sequence++, true, false, ++ key->cipher == WLAN_CIPHER_SUITE_TKIP, ++ mac->join_ap, key->keyidx, key->key, ++ mac->join_credit_deadline); ++ mt6797_mac_join_refused(mac, ret); ++ if (!ret) ++ ret = mt6797_mac_join_wait_credit(mac); ++ mac->gtk_rekey_pending = false; ++ if (ret || mac->ccmp_closed || mac->first_error || mac->closing || ++ mac->join_retired || !mac->join_data_phase || mac->join_data_ended) { ++ if (!ret) ++ ret = mac->first_error ? mac->first_error : -EOPNOTSUPP; ++ goto failed; ++ } ++ mt6797_copy_key_seq(key->cipher, &seed, mac->ccmp_gtk_rx.pn); ++ for (tid = 1; tid < MT6797_CCMP_RX_TIDS; tid++) ++ mt6797_copy_key_seq(key->cipher, &tid_seed[tid - 1], ++ mac->ccmp_gtk_rx.tid_pn[tid - 1]); ++ memcpy(mac->ccmp_gtk_rx.own, hw->wiphy->perm_addr, 6); ++ memcpy(mac->ccmp_gtk_rx.ap, mac->join_ap, 6); ++ mac->ccmp_gtk_rx.cipher = key->cipher; ++ mac->ccmp_gtk_rx.key_bytes = key->keylen; ++ mac->ccmp_gtk_rx.key_id = key->keyidx; ++ mac->ccmp_gtk_rx.wlan_index = MT6797_JOIN_BMC_WLAN_INDEX; ++ mac->ccmp_gtk_rx.rxd_bssid = 1; ++ mac->ccmp_gtk_rx.channel = mac->join_chan_number; ++ mac->ccmp_gtk_rx.pairwise = false; ++ mac->ccmp_gtk_rx.seeded = true; ++ mac->ccmp_gtk_rx.authorized = mac->ccmp_rx.authorized; ++ mac->ccmp_gtk_rx.active = true; ++ key->hw_key_idx = MT6797_JOIN_BMC_WLAN_INDEX; ++ spin_lock_irqsave(&mac->join_queue.lock, flags); ++ mac->ccmp_gtk = key; ++ spin_unlock_irqrestore(&mac->join_queue.lock, flags); ++ mac->join_key_group = 1; ++ mac->join_group_key_id = key->keyidx; ++ mac->ccmp_live_keys++; ++ schedule_delayed_work(&mac->join_work, 0); ++ dev_info(wiphy_dev(hw->wiphy), ++ "one-shot WLAN GTK rekey installed in-place: keyidx=%d sequence=%u\n", ++ key->keyidx, mac->sequence - 1); ++ mutex_unlock(&mac->mutex); ++ return 0; ++ } + if ((mac->ccmp_closed || + (pairwise && mac->ccmp_ptk_attempted) || + (!pairwise && mac->ccmp_gtk_attempted))) { +@@ -2051,6 +2191,7 @@ + struct ieee80211_key_conf *deferred = mac->ccmp_gtk_deferred; + + mac->join_key_pairwise = 1; ++ mac->ccmp_live_keys++; + mac->ccmp_gtk_deferred = NULL; + mutex_unlock(&mac->mutex); + /* A failure ends the lifetime there; the pairwise key stands. */ +@@ -2059,6 +2200,7 @@ + return 0; + } else { + mac->join_key_group = 1; ++ mac->ccmp_live_keys++; + mac->join_group_key_id = key->keyidx; + /* Both keys installed: open the bounded data phase inside the + * grant; the reserved deauthentication waits for its end and +@@ -2435,14 +2577,12 @@ + * reported. Anything else below the admission is freed unsent. + */ + if (skb->len >= sizeof(header) && skb->len <= sizeof(header) + 1500 && +- !(IEEE80211_SKB_CB(skb)->control.flags & IEEE80211_TX_CTRL_PORT_CTRL_PROTO) && + IEEE80211_SKB_CB(skb)->control.hw_key && + !skb_copy_bits(skb, 0, header, sizeof(header)) && + mt6797_mac_tx_hdrlen(header, &hl) && + (mt6797_join_le16(header) & ~(0x0800U | MT6797_JOIN_TX_QOS_BIT)) == 0x4108 && + !mt6797_join_qos_tid_refused(mac, skb, header, hl) && + !memcmp(header + hl, llc_eapol, 6) && +- !(header[hl + 6] == 0x88 && header[hl + 7] == 0x8e) && + ether_addr_equal(header + 4, mac->join_ap) && + ether_addr_equal(header + 10, hw->wiphy->perm_addr)) { + spin_lock_irqsave(&mac->join_queue.lock, flags); diff --git a/patches/kernel/series b/patches/kernel/series index a348e50..74243b6 100644 --- a/patches/kernel/series +++ b/patches/kernel/series @@ -5,3 +5,5 @@ 0005-mt6797-consys-wifi-factory-firmware.patch 0006-mt6797-boot-cleanups.patch 0007-mt6797-wlan-peer-deauth-and-rekey.patch +0008-gemini-resume-wake-and-spm-standby.patch +0009-mt6797-wlan-drop-free-stability.patch diff --git a/patches/xlibre/0003-fast-90-270-shadow-rotation.patch b/patches/xlibre/0003-fast-90-270-shadow-rotation.patch new file mode 100644 index 0000000..e4773fe --- /dev/null +++ b/patches/xlibre/0003-fast-90-270-shadow-rotation.patch @@ -0,0 +1,235 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Geminux Project +Date: Tue, 24 Nov 2026 10:25:00 +0200 +Subject: [PATCH] geminux: skip redundant shadow->front_bo copy and add 16x16 tiled 32bpp rotation + +--- +diff --git a/hw/xfree86/drivers/video/modesetting/driver.c b/hw/xfree86/drivers/video/modesetting/driver.c +--- a/hw/xfree86/drivers/video/modesetting/driver.c ++++ b/hw/xfree86/drivers/video/modesetting/driver.c +@@ -1666,6 +1666,28 @@ + { + ScrnInfoPtr pScrn = xf86ScreenToScrn(pScreen); + modesettingPtr ms = modesettingPTR(pScrn); ++ xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn); ++ ++ if (xf86_config && xf86_config->num_crtc > 0) { ++ int enabled_crtcs = 0; ++ Bool all_rotated = TRUE; ++ ++ for (int c = 0; c < xf86_config->num_crtc; c++) { ++ xf86CrtcPtr crtc = xf86_config->crtc[c]; ++ if (!crtc || !crtc->enabled) ++ continue; ++ enabled_crtcs++; ++ if (!crtc->transform_in_use || !crtc->rotatedPixmap) { ++ all_rotated = FALSE; ++ break; ++ } ++ } ++ if (enabled_crtcs > 0 && all_rotated) { ++ DamageEmpty(pBuf->pDamage); ++ return; ++ } ++ } ++ + bool use_3224 = ms->drmmode.force_24_32 && pScrn->bitsPerPixel == 32; + + if (ms->drmmode.shadow_enable2 && ms->drmmode.shadow_fb2) do { +diff --git a/hw/xfree86/modes/xf86Rotate.c b/hw/xfree86/modes/xf86Rotate.c +--- a/hw/xfree86/modes/xf86Rotate.c ++++ b/hw/xfree86/modes/xf86Rotate.c +@@ -23,6 +23,7 @@ + #include + + #include ++#include + #include + #include + #include +@@ -40,6 +41,174 @@ + #include "xf86Modes.h" + #include "xf86RandR12.h" + ++static inline void ++xf86RotateBlitRect32(Rotation rot, ++ const uint32_t *src_base, size_t src_stride32, ++ uint32_t *dst_base, size_t dst_stride32, ++ int crtc_x, int crtc_y, int W, int H, ++ int x1, int y1, int x2, int y2) ++{ ++ if (rot == RR_Rotate_270) { ++ for (int ty = y1; ty < y2; ty += 16) { ++ int bh = (y2 - ty < 16) ? (y2 - ty) : 16; ++ for (int tx = x1; tx < x2; tx += 16) { ++ int bw = (x2 - tx < 16) ? (x2 - tx) : 16; ++ uint32_t tile[16][16]; ++ ++ for (int bx = 0; bx < bw; bx++) { ++ const uint32_t *srow = src_base + ++ (size_t)(crtc_y + (W - 1 - (tx + bx))) * src_stride32 + ++ (size_t)(crtc_x + ty); ++ for (int by = 0; by < bh; by++) ++ tile[by][bx] = srow[by]; ++ } ++ for (int by = 0; by < bh; by++) { ++ uint32_t *drow = dst_base + ++ (size_t)(ty + by) * dst_stride32 + (size_t)tx; ++ memcpy(drow, tile[by], (size_t)bw * sizeof(uint32_t)); ++ } ++ } ++ } ++ } else if (rot == RR_Rotate_90) { ++ for (int ty = y1; ty < y2; ty += 16) { ++ int bh = (y2 - ty < 16) ? (y2 - ty) : 16; ++ for (int tx = x1; tx < x2; tx += 16) { ++ int bw = (x2 - tx < 16) ? (x2 - tx) : 16; ++ uint32_t tile[16][16]; ++ ++ for (int bx = 0; bx < bw; bx++) { ++ const uint32_t *srow = src_base + ++ (size_t)(crtc_y + tx + bx) * src_stride32 + ++ (size_t)(crtc_x + H - ty - bh); ++ for (int k = 0; k < bh; k++) ++ tile[bh - 1 - k][bx] = srow[k]; ++ } ++ for (int by = 0; by < bh; by++) { ++ uint32_t *drow = dst_base + ++ (size_t)(ty + by) * dst_stride32 + (size_t)tx; ++ memcpy(drow, tile[by], (size_t)bw * sizeof(uint32_t)); ++ } ++ } ++ } ++ } else { ++ for (int dy = y1; dy < y2; dy++) { ++ const uint32_t *srow = src_base + ++ (size_t)(crtc_y + H - 1 - dy) * src_stride32 + ++ (size_t)(crtc_x + W - 1); ++ uint32_t *drow = dst_base + (size_t)dy * dst_stride32; ++ uint32_t rowbuf[64]; ++ ++ for (int tx = x1; tx < x2; tx += 64) { ++ int bw = (x2 - tx < 64) ? (x2 - tx) : 64; ++ for (int k = 0; k < bw; k++) ++ rowbuf[k] = srow[-(tx + k)]; ++ memcpy(drow + tx, rowbuf, (size_t)bw * sizeof(uint32_t)); ++ } ++ } ++ } ++} ++ ++static Bool ++xf86RotateTryFast32(xf86CrtcPtr crtc, PixmapPtr dst_pixmap, ++ DrawableRec *src_drawable, RegionPtr region, ++ Bool transform_src) ++{ ++ ScrnInfoPtr scrn = crtc->scrn; ++ ScreenPtr screen = scrn->pScreen; ++ Rotation rot = crtc->rotation & 0xf; ++ int W = crtc->mode.HDisplay; ++ int H = crtc->mode.VDisplay; ++ PixmapPtr src_pixmap; ++ const uint32_t *src_base; ++ uint32_t *dst_base; ++ size_t src_stride32, dst_stride32; ++ int n = RegionNumRects(region); ++ BoxPtr b = RegionRects(region); ++ ++ if (!transform_src || crtc->transformPresent || crtc->filter) ++ return FALSE; ++ if (crtc->rotation & (RR_Reflect_X | RR_Reflect_Y)) ++ return FALSE; ++ if (rot != RR_Rotate_270 && rot != RR_Rotate_90 && rot != RR_Rotate_180) ++ return FALSE; ++ if (W <= 0 || H <= 0) ++ return FALSE; ++ ++ if (src_drawable->type == DRAWABLE_PIXMAP) ++ src_pixmap = (PixmapPtr)src_drawable; ++ else ++ src_pixmap = (*screen->GetWindowPixmap)((WindowPtr)src_drawable); ++ ++ if (!src_pixmap || !dst_pixmap || ++ !src_pixmap->devPrivate.ptr || !dst_pixmap->devPrivate.ptr) ++ return FALSE; ++ if (src_pixmap->drawable.bitsPerPixel != 32 || ++ dst_pixmap->drawable.bitsPerPixel != 32) ++ return FALSE; ++ if ((src_pixmap->devKind & 3) != 0 || (dst_pixmap->devKind & 3) != 0) ++ return FALSE; ++ if (src_drawable->x != 0 || src_drawable->y != 0) ++ return FALSE; ++ if (src_drawable->type != DRAWABLE_PIXMAP && ++ (src_pixmap->screen_x != 0 || src_pixmap->screen_y != 0)) ++ return FALSE; ++ if (W > dst_pixmap->drawable.width || H > dst_pixmap->drawable.height) ++ return FALSE; ++ ++ if (rot == RR_Rotate_90 || rot == RR_Rotate_270) { ++ if (crtc->x < 0 || crtc->y < 0 || ++ crtc->x + H > src_pixmap->drawable.width || ++ crtc->y + W > src_pixmap->drawable.height) ++ return FALSE; ++ } else { ++ if (crtc->x < 0 || crtc->y < 0 || ++ crtc->x + W > src_pixmap->drawable.width || ++ crtc->y + H > src_pixmap->drawable.height) ++ return FALSE; ++ } ++ ++ if (screen->SourceValidate) ++ (*screen->SourceValidate)(src_drawable, 0, 0, ++ src_drawable->width, src_drawable->height, ++ IncludeInferiors); ++ ++ src_base = (const uint32_t *)src_pixmap->devPrivate.ptr; ++ dst_base = (uint32_t *)dst_pixmap->devPrivate.ptr; ++ src_stride32 = (size_t)src_pixmap->devKind >> 2; ++ dst_stride32 = (size_t)dst_pixmap->devKind >> 2; ++ ++ if (crtc->shadowClear) { ++ xf86RotateBlitRect32(rot, src_base, src_stride32, dst_base, dst_stride32, ++ crtc->x, crtc->y, W, H, 0, 0, W, H); ++ crtc->shadowClear = FALSE; ++ return TRUE; ++ } ++ ++ while (n--) { ++ BoxRec dst_box = *b++; ++ ++ pixman_f_transform_bounds(&crtc->f_framebuffer_to_crtc, &dst_box); ++ if (dst_box.x1 < 0) ++ dst_box.x1 = 0; ++ if (dst_box.y1 < 0) ++ dst_box.y1 = 0; ++ if (dst_box.x2 > W) ++ dst_box.x2 = W; ++ if (dst_box.y2 > H) ++ dst_box.y2 = H; ++ ++ if (dst_box.x1 < dst_box.x2 && dst_box.y1 < dst_box.y2) { ++ xf86RotateBlitRect32(rot, src_base, src_stride32, ++ dst_base, dst_stride32, ++ crtc->x, crtc->y, W, H, ++ dst_box.x1, dst_box.y1, ++ dst_box.x2, dst_box.y2); ++ } ++ } ++ ++ return TRUE; ++} ++ + void + xf86RotateCrtcRedisplay(xf86CrtcPtr crtc, PixmapPtr dst_pixmap, + DrawableRec *src_drawable, RegionPtr region, +@@ -57,6 +226,10 @@ + if (crtc->driverIsPerformingTransform & XF86DriverTransformOutput) + return; + ++ if (xf86RotateTryFast32(crtc, dst_pixmap, src_drawable, region, ++ transform_src)) ++ return; ++ + src = CreatePicture(None, + src_drawable, + format, diff --git a/prebuilt/dunst/etc/dunst/dunstrc b/prebuilt/dunst/etc/dunst/dunstrc index 2430b93..ccb750b 100644 --- a/prebuilt/dunst/etc/dunst/dunstrc +++ b/prebuilt/dunst/etc/dunst/dunstrc @@ -2,21 +2,25 @@ [global] monitor = 0 follow = mouse - width = 560 - height = (0, 220) - origin = top-right - offset = (16, 48) + width = 720 + height = (0, 360) + origin = top-center + offset = (0, 96) notification_limit = 5 progress_bar = true - padding = 12 - horizontal_padding = 16 - text_icon_padding = 12 - frame_width = 2 + progress_bar_height = 18 + progress_bar_frame_width = 2 + progress_bar_min_width = 560 + progress_bar_max_width = 660 + padding = 18 + horizontal_padding = 22 + text_icon_padding = 16 + frame_width = 3 frame_color = "#59c2ff" separator_color = "#283444" - corner_radius = 6 + corner_radius = 0 idle_threshold = 120 - font = Fira Code 12.1 + font = Fira Code 34px markup = full format = "%s\n%b" alignment = left @@ -24,7 +28,7 @@ show_age_threshold = 60 word_wrap = yes icon_position = left - max_icon_size = 48 + max_icon_size = 64 dmenu = /usr/bin/dmenu -p dunst: mouse_left_click = do_action, close_current mouse_middle_click = close_current @@ -47,3 +51,17 @@ foreground = "#ffffff" frame_color = "#f07178" timeout = 0 + +[osd] + appname = "geminux-osd" + alignment = center + background = "#161d26" + foreground = "#ffffff" + highlight = "#59c2ff" + frame_color = "#59c2ff" + history_ignore = yes + +[osd_single] + appname = "geminux-osd" + body = "" + format = "%s" diff --git a/prebuilt/dunst/usr/bin/dunst b/prebuilt/dunst/usr/bin/dunst index 2a729cc..b41e85e 100755 Binary files a/prebuilt/dunst/usr/bin/dunst and b/prebuilt/dunst/usr/bin/dunst differ diff --git a/prebuilt/geminux/usr/bin/geminux-camera b/prebuilt/geminux/usr/bin/geminux-camera index 6fa9e7f..1d2daa4 100755 Binary files a/prebuilt/geminux/usr/bin/geminux-camera and b/prebuilt/geminux/usr/bin/geminux-camera differ diff --git a/prebuilt/geminux/usr/bin/geminux-control b/prebuilt/geminux/usr/bin/geminux-control index 6fa719a..865e0af 100755 Binary files a/prebuilt/geminux/usr/bin/geminux-control and b/prebuilt/geminux/usr/bin/geminux-control differ diff --git a/prebuilt/geminux/usr/bin/geminux-lock b/prebuilt/geminux/usr/bin/geminux-lock index 4e450e1..491e0d8 100755 Binary files a/prebuilt/geminux/usr/bin/geminux-lock and b/prebuilt/geminux/usr/bin/geminux-lock differ diff --git a/prebuilt/geminux/usr/bin/geminux-media-key b/prebuilt/geminux/usr/bin/geminux-media-key new file mode 100755 index 0000000..5efa5b5 Binary files /dev/null and b/prebuilt/geminux/usr/bin/geminux-media-key differ diff --git a/prebuilt/geminux/usr/lib/libgemui.so b/prebuilt/geminux/usr/lib/libgemui.so index 39be64a..faa3c0e 100755 Binary files a/prebuilt/geminux/usr/lib/libgemui.so and b/prebuilt/geminux/usr/lib/libgemui.so differ diff --git a/prebuilt/geminux/usr/sbin/geminux-powerd b/prebuilt/geminux/usr/sbin/geminux-powerd index 3f557ae..8174b8b 100755 Binary files a/prebuilt/geminux/usr/sbin/geminux-powerd and b/prebuilt/geminux/usr/sbin/geminux-powerd differ diff --git a/prebuilt/kernel/boot/Image.gz b/prebuilt/kernel/boot/Image.gz index c10e1a8..ca98233 100644 Binary files a/prebuilt/kernel/boot/Image.gz and b/prebuilt/kernel/boot/Image.gz differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/gpu/drm/mediatek/mediatek-drm.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/gpu/drm/mediatek/mediatek-drm.ko.zst index 4a16ebe..56f7e11 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/gpu/drm/mediatek/mediatek-drm.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/gpu/drm/mediatek/mediatek-drm.ko.zst differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/gpu/drm/panel/panel-novatek-nt36672e.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/gpu/drm/panel/panel-novatek-nt36672e.ko.zst index 51b3044..a0571db 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/gpu/drm/panel/panel-novatek-nt36672e.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/gpu/drm/panel/panel-novatek-nt36672e.ko.zst differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/input/touchscreen/novatek-nt36xxx.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/input/touchscreen/novatek-nt36xxx.ko.zst index 0b78037..58c090c 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/input/touchscreen/novatek-nt36xxx.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/input/touchscreen/novatek-nt36xxx.ko.zst differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/leds/rgb/leds-aw9120.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/leds/rgb/leds-aw9120.ko.zst index ffc7535..be2fc3d 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/leds/rgb/leds-aw9120.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/leds/rgb/leds-aw9120.ko.zst differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mac.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mac.ko.zst index e3ac98d..b60db3d 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mac.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mac.ko.zst differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mt6797-wlan-core.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mt6797-wlan-core.ko.zst index 458c456..62f6165 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mt6797-wlan-core.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mt6797-wlan-core.ko.zst differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-ccci-cldma.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-ccci-cldma.ko.zst index 928bc85..87b692d 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-ccci-cldma.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-ccci-cldma.ko.zst differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-spm-sleep.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-spm-sleep.ko.zst index dfc0b26..8096c55 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-spm-sleep.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-spm-sleep.ko.zst differ diff --git a/prebuilt/mpv/etc/mpv/mpv.conf b/prebuilt/mpv/etc/mpv/mpv.conf index 47d750c..a3e08f2 100644 --- a/prebuilt/mpv/etc/mpv/mpv.conf +++ b/prebuilt/mpv/etc/mpv/mpv.conf @@ -5,3 +5,4 @@ gpu-context=x11egl ao=pipewire,pulse,alsa vd-lavc-threads=4 osc=yes +input-ipc-server=/tmp/geminux-mpv.sock diff --git a/prebuilt/suckless/usr/bin/dwm b/prebuilt/suckless/usr/bin/dwm index 09ecd30..5538eb4 100755 Binary files a/prebuilt/suckless/usr/bin/dwm and b/prebuilt/suckless/usr/bin/dwm differ diff --git a/prebuilt/xlibre/usr/bin/Xorg b/prebuilt/xlibre/usr/bin/Xorg index dd5e0fb..f99d998 100755 Binary files a/prebuilt/xlibre/usr/bin/Xorg and b/prebuilt/xlibre/usr/bin/Xorg differ diff --git a/prebuilt/xlibre/usr/lib/xorg/modules/xlibre-25/drivers/modesetting_drv.so b/prebuilt/xlibre/usr/lib/xorg/modules/xlibre-25/drivers/modesetting_drv.so index 0fa571f..1e31229 100755 Binary files a/prebuilt/xlibre/usr/lib/xorg/modules/xlibre-25/drivers/modesetting_drv.so and b/prebuilt/xlibre/usr/lib/xorg/modules/xlibre-25/drivers/modesetting_drv.so differ diff --git a/scripts/build-dunst.sh b/scripts/build-dunst.sh index 53e9bcc..dcdf3ab 100755 --- a/scripts/build-dunst.sh +++ b/scripts/build-dunst.sh @@ -122,6 +122,273 @@ new2 = """ n->icon = icon_get_for_data(new_icon, &n->icon_id, assert old1 in ntxt and old2 in ntxt ntxt = ntxt.replace(old1, new1).replace(old2, new2) open(notif_p, "w").write(ntxt) + +def must_sub(txt, old, new, label): + assert txt.count(old) == 1, f"{label}: expected 1 match, got {txt.count(old)}" + return txt.replace(old, new) + +draw_p = os.path.join(work, "src", "draw.c") +dtxt = open(draw_p).read() +old_pos = """void calc_window_pos(const struct screen_info *scr, int width, int height, int *ret_x, int *ret_y) +{ + if(!ret_x || !ret_y) + return; + + // horizontal + switch (settings.origin) {""" +new_pos = """void calc_window_pos(const struct screen_info *scr, int width, int height, int *ret_x, int *ret_y) +{ + if(!ret_x || !ret_y) + return; + + enum origin_values eff_origin = settings.origin; + GList *disp = queues_get_displayed(); + if (disp && disp->data) { + const struct notification *n = disp->data; + if (n->appname && strcmp(n->appname, "geminux-osd") == 0) + eff_origin = ORIGIN_CENTER; + } + + // horizontal + switch (eff_origin) {""" +dtxt = must_sub(dtxt, old_pos, new_pos, "draw.c calc_window_pos horiz") +dtxt = must_sub(dtxt, "// vertical\n switch (settings.origin) {", "// vertical\n switch (eff_origin) {", "draw.c calc_window_pos vert") +open(draw_p, "w").write(dtxt) + +x11_p = os.path.join(work, "src", "x11", "x.c") +xtxt = open(x11_p).read() +xtxt = must_sub( + xtxt, + """struct window_x11 { + Window xwin; + cairo_surface_t *root_surface; + cairo_t *c_ctx; + GSource *esrc; + int cur_screen; + bool visible; + struct dimensions dim; +};""", + """struct window_x11 { + Window xwin; + cairo_surface_t *root_surface; + cairo_t *c_ctx; + Pixmap backbuf; + GC gc; + Visual *vis; + int depth; + int bw; + int bh; + bool shaped; + GSource *esrc; + int cur_screen; + bool visible; + struct dimensions dim; +};""", + "x.c struct window_x11", +) +xtxt = must_sub( + xtxt, + """void x_display_surface(cairo_surface_t *srf, window winptr, const struct dimensions *dim) +{ + struct window_x11 *win = (struct window_x11*)winptr; + const struct screen_info *scr = get_active_screen(); + double scale = x_get_scale(); + int x, y; + + calc_window_pos(scr, round(dim->w * scale), round(dim->h * scale), &x, &y); + + x_win_move(win, x, y, round(dim->w * scale), round(dim->h * scale)); + cairo_xlib_surface_set_size(win->root_surface, round(dim->w * scale), round(dim->h * scale)); + + XClearWindow(xctx.dpy, win->xwin); + + cairo_set_source_surface(win->c_ctx, srf, 0, 0); + cairo_paint(win->c_ctx); + cairo_show_page(win->c_ctx); + + if (settings.corner_radius != 0 && ! x_win_composited(win)) + x_win_corners_shape(win, round(dim->corner_radius * scale)); + else + x_win_corners_unshape(win); + + XFlush(xctx.dpy); + +}""", + """void x_display_surface(cairo_surface_t *srf, window winptr, const struct dimensions *dim) +{ + struct window_x11 *win = (struct window_x11*)winptr; + const struct screen_info *scr = get_active_screen(); + double scale = x_get_scale(); + int w = round(dim->w * scale); + int h = round(dim->h * scale); + if (w < 1) w = 1; + if (h < 1) h = 1; + int x, y; + + calc_window_pos(scr, w, h, &x, &y); + + if (!win->backbuf || win->bw != w || win->bh != h) { + if (win->backbuf) + XFreePixmap(xctx.dpy, win->backbuf); + win->backbuf = XCreatePixmap(xctx.dpy, win->xwin, w, h, win->depth); + win->bw = w; + win->bh = h; + } + + cairo_surface_t *bbsrf = cairo_xlib_surface_create(xctx.dpy, win->backbuf, + win->vis, w, h); + cairo_t *bbcr = cairo_create(bbsrf); + cairo_set_operator(bbcr, CAIRO_OPERATOR_SOURCE); + cairo_set_source_surface(bbcr, srf, 0, 0); + cairo_paint(bbcr); + cairo_destroy(bbcr); + cairo_surface_flush(bbsrf); + cairo_surface_destroy(bbsrf); + + XSetWindowBackgroundPixmap(xctx.dpy, win->xwin, win->backbuf); + x_win_move(win, x, y, w, h); + cairo_xlib_surface_set_size(win->root_surface, w, h); + + if (settings.corner_radius != 0 && !x_win_composited(win)) { + x_win_corners_shape(win, round(dim->corner_radius * scale)); + win->shaped = true; + } else if (win->shaped) { + x_win_corners_unshape(win); + win->shaped = false; + } + + if (win->visible) + XCopyArea(xctx.dpy, win->backbuf, win->xwin, win->gc, 0, 0, w, h, 0, 0); + + XFlush(xctx.dpy); +}""", + "x.c x_display_surface", +) +xtxt = must_sub( + xtxt, + """ case Expose: + LOG_D("XEvent: processing '\''Expose'\''"); + if (ev.xexpose.count == 0 && win->visible) { + draw(); + } + break;""", + """ case Expose: + LOG_D("XEvent: processing '\''Expose'\''"); + if (ev.xexpose.count == 0 && win->visible) { + if (win->backbuf && win->bw == win->dim.w && win->bh == win->dim.h) { + XCopyArea(xctx.dpy, win->backbuf, win->xwin, win->gc, + 0, 0, win->bw, win->bh, 0, 0); + XFlush(xctx.dpy); + } else { + draw(); + } + } + break;""", + "x.c Expose handler", +) +xtxt = must_sub( + xtxt, + """ scr_n = DefaultScreen(xctx.dpy); + root = RootWindow(xctx.dpy, scr_n); + if (XMatchVisualInfo(xctx.dpy, scr_n, 32, TrueColor, &vi)) { + vis = vi.visual; + depth = vi.depth; + } else { + vis = DefaultVisual(xctx.dpy, scr_n); + depth = DefaultDepth(xctx.dpy, scr_n); + } + + wa.override_redirect = true; + wa.background_pixmap = None; + wa.background_pixel = 0; + wa.border_pixel = 0; + wa.colormap = XCreateColormap(xctx.dpy, root, vis, AllocNone); + wa.event_mask = + ExposureMask | KeyPressMask | VisibilityChangeMask | + ButtonReleaseMask | FocusChangeMask| StructureNotifyMask; + + const struct screen_info *scr = get_active_screen(); + win->xwin = XCreateWindow(xctx.dpy, + root, + scr->x, + scr->y, + scr->w, + 1, + 0, + depth, + CopyFromParent, + vis, + CWOverrideRedirect | CWBackPixmap | CWBackPixel | CWBorderPixel | CWColormap | CWEventMask, + &wa);""", + """ scr_n = DefaultScreen(xctx.dpy); + root = RootWindow(xctx.dpy, scr_n); + win->cur_screen = scr_n; + if (x_win_composited(win) && XMatchVisualInfo(xctx.dpy, scr_n, 32, TrueColor, &vi)) { + vis = vi.visual; + depth = vi.depth; + } else { + vis = DefaultVisual(xctx.dpy, scr_n); + depth = DefaultDepth(xctx.dpy, scr_n); + } + win->vis = vis; + win->depth = depth; + + wa.override_redirect = true; + wa.background_pixmap = None; + wa.border_pixel = 0; + wa.colormap = (vis == DefaultVisual(xctx.dpy, scr_n)) + ? DefaultColormap(xctx.dpy, scr_n) + : XCreateColormap(xctx.dpy, root, vis, AllocNone); + wa.event_mask = + ExposureMask | KeyPressMask | VisibilityChangeMask | + ButtonReleaseMask | FocusChangeMask| StructureNotifyMask; + + const struct screen_info *scr = get_active_screen(); + win->xwin = XCreateWindow(xctx.dpy, + root, + scr->x, + scr->y, + scr->w, + 1, + 0, + depth, + CopyFromParent, + vis, + CWOverrideRedirect | CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask, + &wa); + win->gc = XCreateGC(xctx.dpy, win->xwin, 0, NULL);""", + "x.c x_win_create", +) +xtxt = must_sub( + xtxt, + """ cairo_destroy(win->c_ctx); + cairo_surface_destroy(win->root_surface); + XDestroyWindow(xctx.dpy, win->xwin);""", + """ cairo_destroy(win->c_ctx); + cairo_surface_destroy(win->root_surface); + if (win->backbuf) + XFreePixmap(xctx.dpy, win->backbuf); + if (win->gc) + XFreeGC(xctx.dpy, win->gc); + XDestroyWindow(xctx.dpy, win->xwin);""", + "x.c x_win_destroy", +) +xtxt = must_sub( + xtxt, + """ XMapRaised(xctx.dpy, win->xwin); + win->visible = true; + + x_display_surface(win->root_surface, win, &win->dim);""", + """ XMapRaised(xctx.dpy, win->xwin); + win->visible = true; + + if (win->backbuf) + XCopyArea(xctx.dpy, win->backbuf, win->xwin, win->gc, + 0, 0, win->bw, win->bh, 0, 0); + XFlush(xctx.dpy);""", + "x.c x_win_show", +) +open(x11_p, "w").write(xtxt) print("PATCHED dunst src OK") PYEOF diff --git a/scripts/build-mpv.sh b/scripts/build-mpv.sh index 106517d..b3cdb9e 100755 --- a/scripts/build-mpv.sh +++ b/scripts/build-mpv.sh @@ -300,6 +300,7 @@ gpu-context=x11egl ao=pipewire,pulse,alsa vd-lavc-threads=4 osc=yes +input-ipc-server=/tmp/geminux-mpv.sock EOF aarch64-alpine-linux-musl-strip --strip-unneeded \ diff --git a/scripts/test-power-policy.py b/scripts/test-power-policy.py index c7fdb12..ebe41b7 100755 --- a/scripts/test-power-policy.py +++ b/scripts/test-power-policy.py @@ -163,23 +163,23 @@ int main(void) { geminux_profile_params_t eco = geminux_policy_params(POWER_PROFILE_ECO, false); assert(strcmp(eco.governor, "schedutil") == 0); assert(!eco.a72_online); - assert(eco.a53_ll_max_khz == 624000UL); - assert(eco.a53_max_khz == 832000UL); + assert(eco.a53_ll_max_khz == 715000UL); + assert(eco.a53_max_khz == 962000UL); assert(eco.suspend_timeout_s > 0); geminux_profile_params_t bal = geminux_policy_params(POWER_PROFILE_BALANCED, false); assert(strcmp(bal.governor, "schedutil") == 0); assert(bal.a72_online); - assert(bal.a53_ll_max_khz == 806000UL); - assert(bal.a53_max_khz == 1092000UL); + assert(bal.a53_ll_max_khz == 897000UL); + assert(bal.a53_max_khz == 1209000UL); geminux_profile_params_t bal_ac = geminux_policy_params(POWER_PROFILE_BALANCED, true); assert(strcmp(bal_ac.governor, "schedutil") == 0); - assert(bal_ac.a53_ll_max_khz == 897000UL); - assert(bal_ac.a53_max_khz == 1209000UL); + assert(bal_ac.a53_ll_max_khz == 1547000UL); + assert(bal_ac.a53_max_khz == 1846000UL); geminux_profile_params_t perf = geminux_policy_params(POWER_PROFILE_PERFORMANCE, true); - assert(strcmp(perf.governor, "schedutil") == 0); + assert(strcmp(perf.governor, "performance") == 0); assert(perf.a72_online); assert(perf.a53_ll_max_khz == 1547000UL); assert(perf.a53_max_khz == 1846000UL); @@ -521,6 +521,92 @@ int main(void) { int rc_cnt = geminux_parse_resolv_conf("# Generated\nnameserver 88.198.92.222\nnameserver 192.71.166.92 # rad\n", rsum, sizeof(rsum)); assert(rc_cnt == 2 && strcmp(rsum, "88.198.92.222, 192.71.166.92") == 0); + + /* MT6351 fuel-gauge persisted state serialization & bounds validation */ + char fg_buf[128]; + uint32_t fg_r = 0, fg_full = 0; + assert(geminux_fg_state_format(245000U, 3812000U, fg_buf, sizeof(fg_buf)) == 0); + assert(strcmp(fg_buf, "learned_resistance_uohm=245000\nlearned_full_uah=3812000\n") == 0); + assert(geminux_fg_state_parse(fg_buf, &fg_r, &fg_full)); + assert(fg_r == 245000U && fg_full == 3812000U); + assert(geminux_fg_state_parse("learned_full_uah=3500000\n learned_resistance_uohm=180000 \r\n", &fg_r, &fg_full)); + assert(fg_r == 180000U && fg_full == 3500000U); + assert(!geminux_fg_state_parse("learned_resistance_uohm=49999\nlearned_full_uah=3500000\n", &fg_r, &fg_full)); + assert(!geminux_fg_state_parse("learned_resistance_uohm=1500001\nlearned_full_uah=3500000\n", &fg_r, &fg_full)); + assert(!geminux_fg_state_parse("learned_resistance_uohm=200000\nlearned_full_uah=999999\n", &fg_r, &fg_full)); + assert(!geminux_fg_state_parse("learned_resistance_uohm=200000\n", &fg_r, &fg_full)); + assert(geminux_fg_state_format(10000U, 3800000U, fg_buf, sizeof(fg_buf)) < 0); + + /* Verify 16x16 tiled 32bpp 90/180/270 rotation math on asymmetric geometry + sub-rects */ + { + enum { SRC_W = 120, SRC_H = 110, CRTC_X = 7, CRTC_Y = 11, W = 53, H = 97 }; + static uint32_t src_fb[SRC_H * SRC_W]; + static uint32_t dst_fast[H * W]; + static uint32_t dst_ref[H * W]; + for (int y = 0; y < SRC_H; y++) { + for (int x = 0; x < SRC_W; x++) { + src_fb[y * SRC_W + x] = ((uint32_t)(y + 1) << 16) | (uint32_t)(x + 1); + } + } + const int rots[3] = { 90, 180, 270 }; + const int bx1[3] = { 0, 13, 32 }; + const int by1[3] = { 0, 15, 48 }; + const int bx2[3] = { W, 51, 53 }; + const int by2[3] = { H, 81, 97 }; + for (int ri = 0; ri < 3; ri++) { + int deg = rots[ri]; + memset(dst_fast, 0xaa, sizeof(dst_fast)); + memset(dst_ref, 0xaa, sizeof(dst_ref)); + for (int bi = 0; bi < 3; bi++) { + int x1 = bx1[bi], y1 = by1[bi], x2 = bx2[bi], y2 = by2[bi]; + for (int dy = y1; dy < y2; dy++) { + for (int dx = x1; dx < x2; dx++) { + int sx = CRTC_X + ((deg == 270) ? dy : (deg == 90) ? (H - 1 - dy) : (W - 1 - dx)); + int sy = CRTC_Y + ((deg == 270) ? (W - 1 - dx) : (deg == 90) ? dx : (H - 1 - dy)); + dst_ref[dy * W + dx] = src_fb[sy * SRC_W + sx]; + } + } + if (deg == 270) { + for (int ty = y1; ty < y2; ty += 16) { + int bh = (y2 - ty < 16) ? (y2 - ty) : 16; + for (int tx = x1; tx < x2; tx += 16) { + int bw = (x2 - tx < 16) ? (x2 - tx) : 16; + uint32_t tile[16][16]; + for (int bx = 0; bx < bw; bx++) { + const uint32_t *srow = src_fb + (size_t)(CRTC_Y + W - 1 - (tx + bx)) * SRC_W + (size_t)(CRTC_X + ty); + for (int by = 0; by < bh; by++) tile[by][bx] = srow[by]; + } + for (int by = 0; by < bh; by++) { + memcpy(dst_fast + (size_t)(ty + by) * W + tx, tile[by], (size_t)bw * sizeof(uint32_t)); + } + } + } + } else if (deg == 90) { + for (int ty = y1; ty < y2; ty += 16) { + int bh = (y2 - ty < 16) ? (y2 - ty) : 16; + for (int tx = x1; tx < x2; tx += 16) { + int bw = (x2 - tx < 16) ? (x2 - tx) : 16; + uint32_t tile[16][16]; + for (int bx = 0; bx < bw; bx++) { + const uint32_t *srow = src_fb + (size_t)(CRTC_Y + tx + bx) * SRC_W + (size_t)(CRTC_X + H - ty - bh); + for (int k = 0; k < bh; k++) tile[bh - 1 - k][bx] = srow[k]; + } + for (int by = 0; by < bh; by++) { + memcpy(dst_fast + (size_t)(ty + by) * W + tx, tile[by], (size_t)bw * sizeof(uint32_t)); + } + } + } + } else { + for (int dy = y1; dy < y2; dy++) { + const uint32_t *srow = src_fb + (size_t)(CRTC_Y + H - 1 - dy) * SRC_W + (size_t)(CRTC_X + W - 1); + uint32_t *drow = dst_fast + (size_t)dy * W; + for (int dx = x1; dx < x2; dx++) drow[dx] = srow[-dx]; + } + } + } + assert(memcmp(dst_fast, dst_ref, sizeof(dst_ref)) == 0); + } + } return 0; } """ @@ -577,10 +663,16 @@ def main(): 'GEMINUX_ENABLE_CPUFREQ="yes"', 'GEMINUX_ENABLE_SENSORS="no"', 'GEMINUX_GATE_UNUSED_CLOCKS="yes"', + 'GEMINUX_ENABLE_SPM_SLEEP="yes"', ), os.path.join(overlay_dir, "etc", "modprobe.d", "geminux.conf"): ( "blacklist stk3310", "softdep cpufreq_dt pre: clk_mt6797_mcusys", + "options mt6797_spm_sleep sodi_idle=0 pmic_modes=1 timer_sec=600", + "options mt6797_wlan power_save=0", + ), + os.path.join(BASE_DIR, "patches", "kernel", "series"): ( + "0009-mt6797-wlan-drop-free-stability.patch", ), os.path.join(overlay_dir, "etc", "profile.d", "10-geminux-env.sh"): ( "export NO_AT_BRIDGE=1", @@ -606,13 +698,25 @@ def main(): assert trig_idx >= 0, "trigger_suspend missing in geminux-powerd.c" trig_src = powerd_src[trig_idx:] prep_idx = trig_src.find("prepare_consys_for_suspend(") + cpu_prep_idx = trig_src.find("prepare_cpus_for_suspend(") susp_idx = trig_src.find('"/sys/power/state"') + cpu_rest_idx = trig_src.find("restore_cpus_after_resume(") rest_idx = trig_src.find("restore_consys_after_resume(") - if prep_idx < 0 or susp_idx < 0 or rest_idx < 0 or not (prep_idx < susp_idx < rest_idx): - raise AssertionError("trigger_suspend must unload CONSYS before /sys/power/state and restore it after") + if min(prep_idx, cpu_prep_idx, susp_idx, cpu_rest_idx, rest_idx) < 0 or not ( + prep_idx < cpu_prep_idx < susp_idx < cpu_rest_idx < rest_idx): + raise AssertionError("trigger_suspend must quiesce CONSYS and CPUs before /sys/power/state and restore after") if '"mt6797_consys"' not in powerd_src or '"mt6797-consys"' not in powerd_src: raise AssertionError("geminux-powerd.c must unload mt6797_consys and reload mt6797-consys") + with open(os.path.join(APPS_DIR, "geminux-control.c"), "r", encoding="utf-8") as handle: + ctrl_src = handle.read() + if "st->bl_path" not in ctrl_src or "flush_vol_helper(" not in ctrl_src: + raise AssertionError("geminux-control.c must write backlight directly via bl_path and throttle wpctl") + with open(os.path.join(BASE_DIR, "src", "libgemui", "gemui.c"), "r", encoding="utf-8") as handle: + gemui_src = handle.read() + if "XPeekEvent(" not in gemui_src: + raise AssertionError("gemui.c must coalesce consecutive MotionNotify events with XPeekEvent") + print("[PASS] Zero-poll daemon loops, power/lid policy, and touch gestures verified") return 0 diff --git a/scripts/test-xkb-keymap.py b/scripts/test-xkb-keymap.py index 8883014..e9ebf69 100755 --- a/scripts/test-xkb-keymap.py +++ b/scripts/test-xkb-keymap.py @@ -48,6 +48,11 @@ cat /tmp/gemini_dump.xkb "asciitilde", "EuroSign", "Super_L", "ISO_Level3_Shift", "Mod4", "Mod5", "GEMINUX_LALT", "GEMINUX_FN", "SetMods(modifiers=Mod4)", 'include "complete+custom"', + "XF86AudioLowerVolume", "XF86AudioRaiseVolume", "XF86AudioMute", + "XF86MonBrightnessDown", "XF86MonBrightnessUp", "Print", + "XF86AudioPlay", "XF86AudioPrev", "XF86AudioNext", "XF86AudioRecord", + "XF86Sleep", "XF86PowerDown", "XF86Tools", + "XF86TaskPane", "XF86TopMenu", "XF86UWB", "XF86Option", ] for token in checks: assert token in dump, f"Expected '{token}' in compiled XKB dump" @@ -55,7 +60,18 @@ cat /tmp/gemini_dump.xkb assert "[ 1, exclam, F1, asciitilde ]" in dump or \ "1, exclam, F1, asciitilde" in " ".join(dump.split()), \ "AE01 digit/F1/tilde mapping mismatch" - print("[PASS] XKB compilation & Fn+Alt=Mod4 / Fn+1..0=F1..F10 / Shift+Fn+1..0 symbols verified") + + with open(os.path.join(BASE_DIR, "src", "dwm", "dwm.c"), "r", encoding="utf-8") as f: + dwm_src = f.read() + for needle in ("sym_lvl2", "sym_lvl3", "!(ev->state & (Mod4Mask | Mod1Mask))"): + assert needle in dwm_src, f"src/dwm/dwm.c missing {needle!r}" + + with open(os.path.join(BASE_DIR, "src", "dwm", "config.def.h"), "r", encoding="utf-8") as f: + cfg_src = f.read() + for needle in ("geminux-media-key", "XF86XK_AudioRaiseVolume", "XF86XK_MonBrightnessUp", "XK_Print"): + assert needle in cfg_src, f"src/dwm/config.def.h missing {needle!r}" + + print("[PASS] XKB compilation, Fn+Alt=Mod4, Fn+1..0, and DWM Level 3/4 media keys verified") return 0 diff --git a/src/dwm/config.def.h b/src/dwm/config.def.h index 7558743..57a04fe 100644 --- a/src/dwm/config.def.h +++ b/src/dwm/config.def.h @@ -73,22 +73,19 @@ static const char *audiocmd[] = { "geminux-audio", NULL }; static const char *cameracmd[] = { "geminux-camera", NULL }; static const char *themescmd[] = { "geminux-themes", NULL }; static const char *lockcmd[] = { "geminux-lock", NULL }; -static const char *shotcmd[] = { - "/bin/sh", "-c", - "mkdir -p ~/Pictures && scrot ~/Pictures/screenshot-$(date +%Y%m%d-%H%M%S).png", - NULL -}; -static const char *briupcmd[] = { "brightnessctl", "set", "+10%", NULL }; -static const char *bridowncmd[] = { "brightnessctl", "set", "10%-", NULL }; -static const char *volupcmd[] = { - "/bin/sh", "-c", "wpctl set-volume -l 1.0 @DEFAULT_AUDIO_SINK@ 5%+ && pkill -USR1 geminux-statusd || true", NULL -}; -static const char *voldowncmd[] = { - "/bin/sh", "-c", "wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%- && pkill -USR1 geminux-statusd || true", NULL -}; -static const char *volmutecmd[] = { - "/bin/sh", "-c", "wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle && pkill -USR1 geminux-statusd || true", NULL -}; +static const char *shotcmd[] = { "geminux-media-key", "screenshot", NULL }; +static const char *shotwincmd[] = { "geminux-media-key", "screenshot-window", NULL }; +static const char *briupcmd[] = { "geminux-media-key", "bri-up", NULL }; +static const char *bridowncmd[] = { "geminux-media-key", "bri-down", NULL }; +static const char *volupcmd[] = { "geminux-media-key", "vol-up", NULL }; +static const char *voldowncmd[] = { "geminux-media-key", "vol-down", NULL }; +static const char *volmutecmd[] = { "geminux-media-key", "vol-mute", NULL }; +static const char *micmutecmd[] = { "geminux-media-key", "mic-mute", NULL }; +static const char *playpausecmd[] = { "geminux-media-key", "play-pause", NULL }; +static const char *medprevcmd[] = { "geminux-media-key", "prev", NULL }; +static const char *mednextcmd[] = { "geminux-media-key", "next", NULL }; +static const char *medstopcmd[] = { "geminux-media-key", "stop", NULL }; +static const char *suspendcmd[] = { "doas", "/usr/bin/geminux-power-ctl", "suspend", NULL }; static const Key keys[] = { /* modifier key function argument */ @@ -107,11 +104,28 @@ static const Key keys[] = { { MODKEY|ShiftMask, XK_l, spawn, {.v = lockcmd} }, { 0, XF86XK_ScreenSaver, spawn, {.v = lockcmd} }, { 0, XK_Print, spawn, {.v = shotcmd} }, + { ControlMask, XK_Print, spawn, {.v = shotwincmd} }, + { ShiftMask, XK_Print, spawn, {.v = shotwincmd} }, { 0, XF86XK_MonBrightnessUp, spawn, {.v = briupcmd} }, { 0, XF86XK_MonBrightnessDown, spawn, {.v = bridowncmd} }, { 0, XF86XK_AudioRaiseVolume, spawn, {.v = volupcmd} }, { 0, XF86XK_AudioLowerVolume, spawn, {.v = voldowncmd} }, { 0, XF86XK_AudioMute, spawn, {.v = volmutecmd} }, + { 0, XF86XK_AudioRecord, spawn, {.v = micmutecmd} }, + { 0, XF86XK_AudioMicMute, spawn, {.v = micmutecmd} }, + { 0, XF86XK_AudioPlay, spawn, {.v = playpausecmd} }, + { 0, XF86XK_AudioPause, spawn, {.v = playpausecmd} }, + { 0, XF86XK_AudioPrev, spawn, {.v = medprevcmd} }, + { 0, XF86XK_AudioNext, spawn, {.v = mednextcmd} }, + { 0, XF86XK_AudioStop, spawn, {.v = medstopcmd} }, + { 0, XF86XK_Tools, spawn, {.v = controlcmd} }, + { 0, XF86XK_Option, spawn, {.v = audiocmd} }, + { 0, XF86XK_TaskPane, spawn, {.v = launchercmd} }, + { 0, XF86XK_TopMenu, spawn, {.v = launchercmd} }, + { 0, XF86XK_UWB, spawn, {.v = netcmd} }, + { 0, XF86XK_WLAN, spawn, {.v = netcmd} }, + { 0, XF86XK_Sleep, spawn, {.v = suspendcmd} }, + { 0, XF86XK_PowerDown, spawn, {.v = controlcmd} }, { MODKEY, XK_b, togglebar, {0} }, { MODKEY, XK_j, focusstack, {.i = +1} }, { MODKEY, XK_k, focusstack, {.i = -1} }, diff --git a/src/dwm/dwm.c b/src/dwm/dwm.c index a0d3ce8..02e15c6 100644 --- a/src/dwm/dwm.c +++ b/src/dwm/dwm.c @@ -970,18 +970,39 @@ static void grabkeys(void) { } } + int min_kc = 8, max_kc = 255; + XDisplayKeycodes(dpy, &min_kc, &max_kc); + for (i = 0; i < LENGTH(keys); i++) { - KeyCode kc = XKeysymToKeycode(dpy, keys[i].keysym); - if (!kc) continue; - for (j = 0; j < LENGTH(modifiers); j++) { - XGrabKey(dpy, kc, keys[i].mod | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); - if (keys[i].mod & Mod4Mask) { - /* Fn+Alt frequently preserves Mod1Mask and/or Mod5Mask alongside Mod4Mask under XKB */ - XGrabKey(dpy, kc, keys[i].mod | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); - XGrabKey(dpy, kc, keys[i].mod | Mod1Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); - XGrabKey(dpy, kc, keys[i].mod | Mod1Mask | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); - if (active_latch) { - XGrabKey(dpy, kc, (keys[i].mod & ~Mod4Mask) | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + int kc_i; + for (kc_i = min_kc; kc_i <= max_kc; kc_i++) { + KeyCode kc = (KeyCode)kc_i; + KeySym s0 = XkbKeycodeToKeysym(dpy, kc, 0, 0); + KeySym s2 = XkbKeycodeToKeysym(dpy, kc, 0, 2); + KeySym s3 = XkbKeycodeToKeysym(dpy, kc, 0, 3); + + if (s0 == keys[i].keysym) { + for (j = 0; j < LENGTH(modifiers); j++) { + XGrabKey(dpy, kc, keys[i].mod | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + if (keys[i].mod & Mod4Mask) { + /* Fn+Alt frequently preserves Mod1Mask and/or Mod5Mask alongside Mod4Mask under XKB */ + XGrabKey(dpy, kc, keys[i].mod | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, kc, keys[i].mod | Mod1Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, kc, keys[i].mod | Mod1Mask | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + if (active_latch) { + XGrabKey(dpy, kc, (keys[i].mod & ~Mod4Mask) | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + } + } + } + } else if (!(keys[i].mod & Mod4Mask) && s2 == keys[i].keysym && s0 != keys[i].keysym) { + /* Grab Fn (ISO_Level3_Shift / Mod5Mask) Layer-3 multimedia/system keys */ + for (j = 0; j < LENGTH(modifiers); j++) { + XGrabKey(dpy, kc, keys[i].mod | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + } + } else if (!(keys[i].mod & Mod4Mask) && s3 == keys[i].keysym && s2 != keys[i].keysym && s0 != keys[i].keysym) { + /* Grab Shift+Fn (ShiftMask | Mod5Mask) Layer-4 keysyms */ + for (j = 0; j < LENGTH(modifiers); j++) { + XGrabKey(dpy, kc, keys[i].mod | ShiftMask | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); } } } @@ -1020,6 +1041,8 @@ static void keypress(XEvent *e) { XKeyEvent *ev = &e->xkey; KeySym sym_ev = XLookupKeysym(ev, 0); KeySym sym0 = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 0); + KeySym sym_lvl2 = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 2); + KeySym sym_lvl3 = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 3); unsigned long long t = now_ms(); int active_latch = super_latched && (t <= super_latch_until); @@ -1038,19 +1061,32 @@ static void keypress(XEvent *e) { } for (i = 0; i < LENGTH(keys); i++) { - if (sym0 != keys[i].keysym && sym_ev != keys[i].keysym) - continue; int matched = 0; - if (CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)) { - matched = 1; - } else if ((keys[i].mod & Mod4Mask) && - CLEANMASK(keys[i].mod) == CLEANMASK(ev->state & ~(Mod1Mask | Mod5Mask))) { - matched = 1; - } else if (active_latch && (keys[i].mod & Mod4Mask) && - CLEANMASK(keys[i].mod & ~Mod4Mask) == CLEANMASK(ev->state & ~(Mod1Mask | Mod5Mask))) { - matched = 1; - super_latched = 0; - grabkeys(); + if (sym0 == keys[i].keysym || sym_ev == keys[i].keysym) { + if (CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)) { + matched = 1; + } else if ((keys[i].mod & Mod4Mask) && + CLEANMASK(keys[i].mod) == CLEANMASK(ev->state & ~(Mod1Mask | Mod5Mask))) { + matched = 1; + } else if (active_latch && (keys[i].mod & Mod4Mask) && + CLEANMASK(keys[i].mod & ~Mod4Mask) == CLEANMASK(ev->state & ~(Mod1Mask | Mod5Mask))) { + matched = 1; + super_latched = 0; + grabkeys(); + } + } + if (!matched && !(keys[i].mod & Mod4Mask) && + (ev->state & Mod5Mask) && !(ev->state & (Mod4Mask | Mod1Mask)) && + sym_lvl2 == keys[i].keysym && sym0 != keys[i].keysym) { + if (CLEANMASK(keys[i].mod) == CLEANMASK(ev->state & ~Mod5Mask)) + matched = 1; + } + if (!matched && !(keys[i].mod & Mod4Mask) && + (ev->state & (ShiftMask | Mod5Mask)) == (ShiftMask | Mod5Mask) && + !(ev->state & (Mod4Mask | Mod1Mask)) && + sym_lvl3 == keys[i].keysym && sym_lvl2 != keys[i].keysym && sym0 != keys[i].keysym) { + if (CLEANMASK(keys[i].mod) == CLEANMASK(ev->state & ~(ShiftMask | Mod5Mask))) + matched = 1; } if (matched && keys[i].func) { keys[i].func(&(keys[i].arg)); @@ -1228,6 +1264,16 @@ static void manage(Window w, XWindowAttributes *wa) { grabbuttons(c, 0); if (!c->isfloating) c->isfloating = c->oldstate = (trans != None || c->isfixed); + if (c->isfloating && !c->isfullscreen && wa->x == 0 && wa->y == 0) { + c->x = c->mon->wx + (c->mon->ww - WIDTH(c)) / 2; + c->y = c->mon->wy + (c->mon->wh - HEIGHT(c)) / 2; + if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww) + c->x = c->mon->wx + c->mon->ww - WIDTH(c); + if (c->y + HEIGHT(c) > c->mon->wy + c->mon->wh) + c->y = c->mon->wy + c->mon->wh - HEIGHT(c); + c->x = MAX(c->x, c->mon->wx); + c->y = MAX(c->y, c->mon->wy); + } if (c->isfloating) XRaiseWindow(dpy, c->win); attach(c); diff --git a/src/geminux-apps/Makefile b/src/geminux-apps/Makefile index 63fdc50..db21f16 100644 --- a/src/geminux-apps/Makefile +++ b/src/geminux-apps/Makefile @@ -18,10 +18,14 @@ APPS = \ geminux-control \ geminux-themes \ geminux-datetime \ - geminux-lock + geminux-lock \ + geminux-media-key all: $(APPS) +geminux-media-key: geminux-media-key.c + $(CC) -std=c11 -Wall -Wextra -O2 -o $@ $< + geminux-datetime: geminux-datetime.c ../geminux-daemons/geminux-tz-valid.h ../libgemui/gemui.h $(CC) $(CFLAGS) -o $@ $< $(LIBS) diff --git a/src/geminux-apps/geminux-control.c b/src/geminux-apps/geminux-control.c index 0702531..ae1ee21 100644 --- a/src/geminux-apps/geminux-control.c +++ b/src/geminux-apps/geminux-control.c @@ -2,9 +2,13 @@ #include "gemui.h" #include +#include #include #include #include +#include +#include +#include #define HIT_BRI 1 #define HIT_VOL 2 @@ -20,9 +24,12 @@ typedef struct { gemui_app_t *app; char bl_dir[256]; + char bl_path[320]; int bl_cur; int bl_max; int vol_pct; + pid_t vol_pid; + int pending_vol_pct; int profile; /* 0=eco, 1=balanced, 2=performance */ gemui_rect_t bri_rect; gemui_rect_t vol_rect; @@ -31,6 +38,7 @@ typedef struct { static void detect_backlight(ctrl_state_t *st) { st->bl_dir[0] = '\0'; + st->bl_path[0] = '\0'; st->bl_cur = 128; st->bl_max = 255; DIR *d = opendir("/sys/class/backlight"); @@ -43,8 +51,8 @@ static void detect_backlight(ctrl_state_t *st) { char p[320]; snprintf(p, sizeof(p), "%s/max_brightness", st->bl_dir); if (gemui_read_file_line(p, b, sizeof(b)) == 0 && atoi(b) > 0) st->bl_max = atoi(b); - snprintf(p, sizeof(p), "%s/brightness", st->bl_dir); - if (gemui_read_file_line(p, b, sizeof(b)) == 0) st->bl_cur = atoi(b); + snprintf(st->bl_path, sizeof(st->bl_path), "%s/brightness", st->bl_dir); + if (gemui_read_file_line(st->bl_path, b, sizeof(b)) == 0) st->bl_cur = atoi(b); break; } closedir(d); @@ -52,11 +60,32 @@ static void detect_backlight(ctrl_state_t *st) { static void refresh_hw(ctrl_state_t *st) { detect_backlight(st); - char out[128] = {0}; - const char *vcmd[] = {"wpctl", "get-volume", "@DEFAULT_AUDIO_SINK@", NULL}; - if (gemui_run_cmd_capture(vcmd, out, sizeof(out)) == 0) { - char *p = strstr(out, "Volume:"); - if (p) st->vol_pct = (int)(atof(p + 7) * 100.0 + 0.5); + bool got_vol = false; + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { + unsigned long long now_ms = (unsigned long long)ts.tv_sec * 1000ULL + + (unsigned long long)(ts.tv_nsec / 1000000L); + char cpath[96]; + snprintf(cpath, sizeof(cpath), "/tmp/geminux-vol-cache-%u", (unsigned)getuid()); + FILE *cf = fopen(cpath, "r"); + if (cf) { + int pct = 0, mut = 0; + unsigned long long cts = 0; + if (fscanf(cf, "%d %d %llu", &pct, &mut, &cts) == 3 && + pct >= 0 && pct <= 200 && now_ms >= cts && (now_ms - cts) <= 4000ULL) { + st->vol_pct = pct; + got_vol = true; + } + fclose(cf); + } + } + if (!got_vol) { + char out[128] = {0}; + const char *vcmd[] = {"wpctl", "get-volume", "@DEFAULT_AUDIO_SINK@", NULL}; + if (gemui_run_cmd_capture(vcmd, out, sizeof(out)) == 0) { + char *p = strstr(out, "Volume:"); + if (p) st->vol_pct = (int)(atof(p + 7) * 100.0 + 0.5); + } } char prof[64] = {0}; if (gemui_read_file_line("/run/geminux/power-profile", prof, sizeof(prof)) == 0) { @@ -66,28 +95,112 @@ static void refresh_hw(ctrl_state_t *st) { } } -static void set_brightness_norm(ctrl_state_t *st, double norm) { - if (norm < 0.05) norm = 0.05; - if (norm > 1.0) norm = 1.0; - st->bl_cur = (int)(norm * st->bl_max); - int pct = (int)(norm * 100.0 + 0.5); +static void dispatch_vol_pct(ctrl_state_t *st, int pct) { + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { + unsigned long long now_ms = (unsigned long long)ts.tv_sec * 1000ULL + + (unsigned long long)(ts.tv_nsec / 1000000L); + char cpath[96], ctmp[112]; + snprintf(cpath, sizeof(cpath), "/tmp/geminux-vol-cache-%u", (unsigned)getuid()); + snprintf(ctmp, sizeof(ctmp), "%s.tmp.%ld", cpath, (long)getpid()); + int cfd = open(ctmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + if (cfd >= 0) { + char cbuf[64]; + int cn = snprintf(cbuf, sizeof(cbuf), "%d 0 %llu\n", pct, now_ms); + if (cn > 0) { + ssize_t cw = write(cfd, cbuf, (size_t)cn); + (void)cw; + } + close(cfd); + if (rename(ctmp, cpath) != 0) unlink(ctmp); + } + } char arg[32]; snprintf(arg, sizeof(arg), "%d%%", pct); - const char *cmd[] = {"brightnessctl", "set", arg, NULL}; - gemui_run_cmd_capture(cmd, NULL, 0); + pid_t pid = fork(); + if (pid < 0) return; + if (pid == 0) { + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + if (devnull != STDIN_FILENO) dup2(devnull, STDIN_FILENO); + if (devnull != STDOUT_FILENO) dup2(devnull, STDOUT_FILENO); + if (devnull != STDERR_FILENO) dup2(devnull, STDERR_FILENO); + if (devnull > 2) close(devnull); + } + const char *cmd[] = {"wpctl", "set-volume", "@DEFAULT_AUDIO_SINK@", arg, NULL}; + execvp(cmd[0], (char *const *)cmd); + _exit(127); + } + st->vol_pid = pid; +} + +static void flush_vol_helper(ctrl_state_t *st) { + if (st->vol_pid > 0) { + int status = 0; + pid_t r = waitpid(st->vol_pid, &status, WNOHANG); + if (r == 0) return; + st->vol_pid = -1; + } + if (st->pending_vol_pct >= 0) { + int pct = st->pending_vol_pct; + st->pending_vol_pct = -1; + dispatch_vol_pct(st, pct); + } +} + +static void on_timer(gemui_app_t *app, void *ud) { + ctrl_state_t *st = ud; + flush_vol_helper(st); + if (st->vol_pid <= 0 && st->pending_vol_pct < 0) { + gemui_set_timer_ms(app, 0, NULL, NULL); + } +} + +static void set_brightness_norm(ctrl_state_t *st, double norm) { + if (norm < 0.01) norm = 0.01; + if (norm > 1.0) norm = 1.0; + if (st->bl_max <= 0) st->bl_max = 255; + int v = (int)(norm * (double)st->bl_max + 0.5); + if (v < 1) v = 1; + if (v > st->bl_max) v = st->bl_max; + if (v == st->bl_cur) return; + + st->bl_cur = v; + bool wrote_sysfs = false; + if (st->bl_path[0]) { + int fd = open(st->bl_path, O_WRONLY | O_CLOEXEC); + if (fd >= 0) { + char buf[32]; + int n = snprintf(buf, sizeof(buf), "%d\n", v); + if (n > 0 && write(fd, buf, (size_t)n) == (ssize_t)n) { + wrote_sysfs = true; + } + close(fd); + } + } + if (!wrote_sysfs) { + int pct = (int)(norm * 100.0 + 0.5); + if (pct < 1) pct = 1; + char arg[32]; + snprintf(arg, sizeof(arg), "%d%%", pct); + const char *cmd[] = {"brightnessctl", "set", arg, NULL}; + gemui_spawn_detached(cmd); + } gemui_request_redraw(st->app); } static void set_volume_norm(ctrl_state_t *st, double norm) { if (norm < 0.0) norm = 0.0; if (norm > 1.0) norm = 1.0; - st->vol_pct = (int)(norm * 100.0 + 0.5); - char arg[32]; - snprintf(arg, sizeof(arg), "%d%%", st->vol_pct); - const char *cmd[] = {"wpctl", "set-volume", "@DEFAULT_AUDIO_SINK@", arg, NULL}; - gemui_run_cmd_capture(cmd, NULL, 0); - const char *pk[] = {"pkill", "-USR1", "geminux-statusd", NULL}; - gemui_run_cmd_capture(pk, NULL, 0); + int pct = (int)(norm * 100.0 + 0.5); + if (pct == st->vol_pct) return; + + st->vol_pct = pct; + st->pending_vol_pct = pct; + flush_vol_helper(st); + if (st->vol_pid > 0) { + gemui_set_timer_ms(st->app, 40, on_timer, st); + } gemui_request_redraw(st->app); } @@ -159,6 +272,7 @@ static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, v (void)btn; ctrl_state_t *st = ud; if (type == GEMUI_PTR_UP) { + if (st->active_drag == HIT_VOL) flush_vol_helper(st); st->active_drag = 0; return; } @@ -219,6 +333,8 @@ int main(void) { ctrl_state_t st; memset(&st, 0, sizeof(st)); st.vol_pct = 50; + st.vol_pid = -1; + st.pending_vol_pct = -1; st.profile = 1; refresh_hw(&st); @@ -228,6 +344,11 @@ int main(void) { gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr }; gemui_set_handlers(st.app, &h, &st); int rc = gemui_run(st.app); + if (st.vol_pid > 0) waitpid(st.vol_pid, NULL, 0); + if (st.pending_vol_pct >= 0) { + dispatch_vol_pct(&st, st.pending_vol_pct); + if (st.vol_pid > 0) waitpid(st.vol_pid, NULL, 0); + } gemui_destroy(st.app); return rc; } diff --git a/src/geminux-apps/geminux-lock.c b/src/geminux-apps/geminux-lock.c index 5a21f0d..dd50aa1 100644 --- a/src/geminux-apps/geminux-lock.c +++ b/src/geminux-apps/geminux-lock.c @@ -23,6 +23,7 @@ typedef struct { int last_min; int last_yday; int timer_ms; + int ready_fd; bool grabbed; bool checking; } lock_state_t; @@ -100,6 +101,17 @@ static void attempt_unlock(lock_state_t *st) { static void on_timer(gemui_app_t *app, void *ud) { lock_state_t *st = ud; + if (st->ready_fd >= 0) { + ssize_t wr = write(st->ready_fd, "1", 1); + (void)wr; + close(st->ready_fd); + st->ready_fd = -1; + int next_ms = st->grabbed ? 15000 : 250; + if (st->timer_ms != next_ms) { + st->timer_ms = next_ms; + gemui_set_timer_ms(app, next_ms, on_timer, st); + } + } if (!st->grabbed) { st->grabbed = gemui_grab_input(app); if (st->grabbed && st->timer_ms != 15000) { @@ -210,6 +222,7 @@ int main(void) { memset(&st, 0, sizeof(st)); st.last_min = -1; st.last_yday = -1; + st.ready_fd = -1; struct passwd *pw = getpwuid(getuid()); snprintf(st.user, sizeof(st.user), "%s", (pw && pw->pw_name) ? pw->pw_name : "user"); refresh_battery(&st); @@ -222,16 +235,15 @@ int main(void) { if (rfd_s && rfd_s[0]) { int rfd = atoi(rfd_s); if (rfd >= 0) { - ssize_t wr = write(rfd, "1", 1); - (void)wr; - close(rfd); + st.ready_fd = rfd; } unsetenv("GEMINUX_LOCK_READY_FD"); } gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr }; gemui_set_handlers(st.app, &h, &st); - st.timer_ms = st.grabbed ? 15000 : 250; + /* Signal readiness after the first on_draw + XFlush completes on Xorg. */ + st.timer_ms = (st.ready_fd >= 0) ? 20 : (st.grabbed ? 15000 : 250); gemui_set_timer_ms(st.app, st.timer_ms, on_timer, &st); int rc = gemui_run(st.app); gemui_ungrab_input(st.app); diff --git a/src/geminux-apps/geminux-media-key.c b/src/geminux-apps/geminux-media-key.c new file mode 100644 index 0000000..c1ec329 --- /dev/null +++ b/src/geminux-apps/geminux-media-key.c @@ -0,0 +1,541 @@ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void redirect_devnull(int keep_stdout) { + int dn = open("/dev/null", O_RDWR); + if (dn >= 0) { + if (dn != STDIN_FILENO) dup2(dn, STDIN_FILENO); + if (!keep_stdout && dn != STDOUT_FILENO) dup2(dn, STDOUT_FILENO); + if (dn != STDERR_FILENO) dup2(dn, STDERR_FILENO); + if (dn > 2) close(dn); + } +} + +static int run_cmd(const char *const argv[], char *out, size_t out_sz) { + int pfd[2] = {-1, -1}; + if (out && out_sz > 0) { + out[0] = '\0'; + if (pipe(pfd) < 0) return -1; + } + pid_t pid = fork(); + if (pid < 0) { + if (pfd[0] >= 0) close(pfd[0]); + if (pfd[1] >= 0) close(pfd[1]); + return -1; + } + if (pid == 0) { + if (pfd[1] >= 0) { + close(pfd[0]); + if (pfd[1] != STDOUT_FILENO) dup2(pfd[1], STDOUT_FILENO); + if (pfd[1] > 2) close(pfd[1]); + redirect_devnull(1); + } else { + redirect_devnull(0); + } + execvp(argv[0], (char *const *)argv); + _exit(127); + } + if (pfd[1] >= 0) close(pfd[1]); + if (pfd[0] >= 0) { + size_t pos = 0; + while (pos + 1 < out_sz) { + ssize_t n = read(pfd[0], out + pos, out_sz - 1 - pos); + if (n < 0) { + if (errno == EINTR) continue; + break; + } + if (n == 0) break; + pos += (size_t)n; + } + out[pos] = '\0'; + close(pfd[0]); + } + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {} + return WIFEXITED(status) ? WEXITSTATUS(status) : -1; +} + +static void spawn_detached(const char *const argv[]) { + pid_t pid = fork(); + if (pid == 0) { + setsid(); + pid_t pid2 = fork(); + if (pid2 == 0) { + redirect_devnull(0); + execvp(argv[0], (char *const *)argv); + _exit(127); + } + _exit(0); + } + if (pid > 0) { + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {} + } +} + +static int read_int_file(const char *path, int *val) { + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + char buf[64]; + ssize_t n = read(fd, buf, sizeof(buf) - 1); + close(fd); + if (n <= 0) return -1; + buf[n] = '\0'; + *val = atoi(buf); + return 0; +} + +static int write_str_file(const char *path, const char *s) { + int fd = open(path, O_WRONLY | O_CLOEXEC); + if (fd < 0) return -1; + size_t len = strlen(s); + ssize_t w = write(fd, s, len); + close(fd); + return (w == (ssize_t)len) ? 0 : -1; +} + +static uint64_t mono_ms(void) { + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; + return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); +} + +static void show_osd(const char *tag, int expire_ms, int pct_hint, + const char *summary, const char *body) { + char tag_hint[64]; + char val_hint[32]; + char exp_str[16]; + const char *rep_id = (strcmp(tag, "screenshot") == 0) ? "9911" : "9910"; + snprintf(tag_hint, sizeof(tag_hint), "string:x-dunst-stack-tag:%s", tag); + snprintf(exp_str, sizeof(exp_str), "%d", expire_ms); + + const char *argv[20]; + int idx = 0; + argv[idx++] = "notify-send"; + argv[idx++] = "-a"; + argv[idx++] = "geminux-osd"; + argv[idx++] = "-u"; + argv[idx++] = "low"; + argv[idx++] = "-r"; + argv[idx++] = rep_id; + argv[idx++] = "-t"; + argv[idx++] = exp_str; + argv[idx++] = "-h"; + argv[idx++] = tag_hint; + if (pct_hint >= 0) { + if (pct_hint > 100) pct_hint = 100; + snprintf(val_hint, sizeof(val_hint), "int:value:%d", pct_hint); + argv[idx++] = "-h"; + argv[idx++] = val_hint; + } + argv[idx++] = summary; + if (body && body[0]) { + argv[idx++] = body; + } + argv[idx] = NULL; + spawn_detached(argv); +} + +static int handle_brightness(bool up) { + char bl_dir[280] = {0}; + DIR *d = opendir("/sys/class/backlight"); + if (d) { + struct dirent *de; + while ((de = readdir(d)) != NULL) { + if (de->d_name[0] == '.') continue; + snprintf(bl_dir, sizeof(bl_dir), "/sys/class/backlight/%s", de->d_name); + break; + } + closedir(d); + } + + int max_bri = 255, cur_bri = 128; + bool direct_ok = false; + char p_bri[320] = {0}, p_max[320] = {0}, p_pwr[320] = {0}; + + if (bl_dir[0]) { + snprintf(p_max, sizeof(p_max), "%s/max_brightness", bl_dir); + snprintf(p_bri, sizeof(p_bri), "%s/brightness", bl_dir); + snprintf(p_pwr, sizeof(p_pwr), "%s/bl_power", bl_dir); + if (read_int_file(p_max, &max_bri) == 0 && max_bri > 0 && + read_int_file(p_bri, &cur_bri) == 0) { + int step = (max_bri * 8 + 50) / 100; + if (step < 1) step = 1; + int min_bri = max_bri / 50; + if (min_bri < 1) min_bri = 1; + int next = up ? (cur_bri + step) : (cur_bri - step); + if (up) { + if (next > max_bri) next = max_bri; + write_str_file(p_pwr, "0\n"); + } else { + if (next < min_bri) next = min_bri; + } + char vbuf[32]; + snprintf(vbuf, sizeof(vbuf), "%d\n", next); + if (write_str_file(p_bri, vbuf) == 0) { + cur_bri = next; + direct_ok = true; + } + } + } + + if (!direct_ok) { + const char *bcmd[] = {"brightnessctl", "set", up ? "+8%" : "8%-", NULL}; + run_cmd(bcmd, NULL, 0); + if (p_bri[0]) read_int_file(p_bri, &cur_bri); + } + + int pct = (max_bri > 0) ? ((cur_bri * 100 + max_bri / 2) / max_bri) : 50; + if (pct < 1) pct = 1; + if (pct > 100) pct = 100; + + char msg[64]; + snprintf(msg, sizeof(msg), "Brightness: %d%%", pct); + show_osd("osd", 1400, pct, msg, NULL); + return 0; +} + +static bool query_wpctl_vol(const char *target, int *pct_out, bool *muted_out) { + char out[128]; + const char *cmd[] = {"wpctl", "get-volume", target, NULL}; + if (run_cmd(cmd, out, sizeof(out)) != 0) return false; + const char *p = strstr(out, "Volume:"); + if (!p) return false; + double v = atof(p + 7); + if (v < 0.0) v = 0.0; + if (v > 2.0) v = 2.0; + *pct_out = (int)(v * 100.0 + 0.5); + *muted_out = (strstr(out, "[MUTED]") != NULL); + return true; +} + +static bool read_vol_cache(int *pct_out, bool *muted_out, uint64_t now) { + char path[96]; + snprintf(path, sizeof(path), "/tmp/geminux-vol-cache-%u", (unsigned)getuid()); + FILE *f = fopen(path, "r"); + if (!f) return false; + int pct = 0, mut = 0; + unsigned long long ts = 0; + bool ok = (fscanf(f, "%d %d %llu", &pct, &mut, &ts) == 3 && + pct >= 0 && pct <= 200 && + now >= ts && (now - ts) <= 4000ULL); + fclose(f); + if (ok) { + *pct_out = pct; + *muted_out = (mut != 0); + } + return ok; +} + +static void write_vol_cache(int pct, bool muted, uint64_t now) { + char path[96], tmp[112]; + snprintf(path, sizeof(path), "/tmp/geminux-vol-cache-%u", (unsigned)getuid()); + snprintf(tmp, sizeof(tmp), "%s.tmp.%ld", path, (long)getpid()); + int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + if (fd < 0) return; + char buf[64]; + int n = snprintf(buf, sizeof(buf), "%d %d %llu\n", pct, muted ? 1 : 0, (unsigned long long)now); + if (n > 0) { + ssize_t w = write(fd, buf, (size_t)n); + (void)w; + } + close(fd); + if (rename(tmp, path) != 0) unlink(tmp); +} + +static int handle_audio(const char *action) { + if (strcmp(action, "mic-mute") == 0) { + const char *mmute[] = {"wpctl", "set-mute", "@DEFAULT_AUDIO_SOURCE@", "toggle", NULL}; + run_cmd(mmute, NULL, 0); + int pct = 0; + bool muted = false; + if (query_wpctl_vol("@DEFAULT_AUDIO_SOURCE@", &pct, &muted)) { + char msg[64]; + if (muted) { + show_osd("osd", 1400, 0, "Microphone: Muted", NULL); + } else { + snprintf(msg, sizeof(msg), "Microphone: Active (%d%%)", pct); + show_osd("osd", 1400, pct, msg, NULL); + } + } else { + show_osd("osd", 1400, -1, "Microphone Toggled", NULL); + } + return 0; + } + + char lock_path[96]; + snprintf(lock_path, sizeof(lock_path), "/tmp/geminux-vol-lock-%u", (unsigned)getuid()); + int lfd = open(lock_path, O_CREAT | O_RDWR | O_CLOEXEC, 0600); + if (lfd >= 0) flock(lfd, LOCK_EX); + + uint64_t now = mono_ms(); + int pct = 50; + bool muted = false; + bool have_state = read_vol_cache(&pct, &muted, now); + if (!have_state) { + have_state = query_wpctl_vol("@DEFAULT_AUDIO_SINK@", &pct, &muted); + } + + if (have_state) { + int new_pct = pct; + bool new_muted = muted; + if (strcmp(action, "vol-up") == 0) { + new_muted = false; + new_pct = (pct + 5 <= 100) ? (pct + 5) : 100; + } else if (strcmp(action, "vol-down") == 0) { + new_pct = (pct >= 5) ? (pct - 5) : 0; + } else if (strcmp(action, "vol-mute") == 0) { + new_muted = !muted; + } + + write_vol_cache(new_pct, new_muted, mono_ms()); + if (lfd >= 0) { + flock(lfd, LOCK_UN); + close(lfd); + lfd = -1; + } + + char msg[64]; + if (new_muted) { + show_osd("osd", 1400, 0, "Audio: Muted", NULL); + } else { + snprintf(msg, sizeof(msg), "Volume: %d%%", new_pct); + show_osd("osd", 1400, new_pct, msg, NULL); + } + + if (new_muted != muted) { + const char *mcmd[] = {"wpctl", "set-mute", "@DEFAULT_AUDIO_SINK@", new_muted ? "1" : "0", NULL}; + run_cmd(mcmd, NULL, 0); + } + if (new_pct != pct) { + char varg[16]; + snprintf(varg, sizeof(varg), "%d%%", new_pct); + const char *vcmd[] = {"wpctl", "set-volume", "-l", "1.0", "@DEFAULT_AUDIO_SINK@", varg, NULL}; + run_cmd(vcmd, NULL, 0); + } + return 0; + } + + if (lfd >= 0) { + flock(lfd, LOCK_UN); + close(lfd); + } + if (strcmp(action, "vol-up") == 0) { + const char *unmute[] = {"wpctl", "set-mute", "@DEFAULT_AUDIO_SINK@", "0", NULL}; + const char *raise[] = {"wpctl", "set-volume", "-l", "1.0", "@DEFAULT_AUDIO_SINK@", "5%+", NULL}; + run_cmd(unmute, NULL, 0); + run_cmd(raise, NULL, 0); + } else if (strcmp(action, "vol-down") == 0) { + const char *lower[] = {"wpctl", "set-volume", "@DEFAULT_AUDIO_SINK@", "5%-", NULL}; + run_cmd(lower, NULL, 0); + } else if (strcmp(action, "vol-mute") == 0) { + const char *mute[] = {"wpctl", "set-mute", "@DEFAULT_AUDIO_SINK@", "toggle", NULL}; + run_cmd(mute, NULL, 0); + } + show_osd("osd", 1400, -1, "Audio Updated", NULL); + return 0; +} + +static int handle_screenshot(bool focused_window) { + const char *home = getenv("HOME"); + if (!home || !home[0]) home = "/home/user"; + + char pic_dir[512]; + snprintf(pic_dir, sizeof(pic_dir), "%s/Pictures", home); + mkdir(pic_dir, 0755); + + time_t now = time(NULL); + struct tm tm_now; + localtime_r(&now, &tm_now); + + char stamp[32]; + strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", &tm_now); + + char path[600]; + snprintf(path, sizeof(path), "%s/screenshot-%s.png", pic_dir, stamp); + for (int i = 1; i <= 99 && access(path, F_OK) == 0; i++) { + snprintf(path, sizeof(path), "%s/screenshot-%s-%d.png", pic_dir, stamp, i); + } + + int rc = -1; + if (focused_window) { + const char *wcmd[] = {"scrot", "-u", path, NULL}; + rc = run_cmd(wcmd, NULL, 0); + } + if (rc != 0) { + const char *fcmd[] = {"scrot", path, NULL}; + rc = run_cmd(fcmd, NULL, 0); + } + if (rc != 0) { + show_osd("screenshot", 2500, -1, "Screenshot failed", "scrot returned an error"); + return 1; + } + + const char *clip[] = {"xclip", "-selection", "clipboard", "-t", "image/png", "-i", path, NULL}; + spawn_detached(clip); + + const char *base = strrchr(path, '/'); + base = base ? base + 1 : path; + char body[320]; + snprintf(body, sizeof(body), "%s (copied to clipboard)", base); + show_osd("screenshot", 2500, -1, "Screenshot saved", body); + return 0; +} + +static bool send_mpv_ipc(const char *json_cmd) { + int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) return false; + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + snprintf(addr.sun_path, sizeof(addr.sun_path), "/tmp/geminux-mpv.sock"); + if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) { + close(fd); + return false; + } + size_t len = strlen(json_cmd); + ssize_t w = send(fd, json_cmd, len, MSG_NOSIGNAL); + close(fd); + return (w == (ssize_t)len); +} + +static char read_proc_state(const char *pid_str) { + char path[280], buf[512]; + snprintf(path, sizeof(path), "/proc/%s/stat", pid_str); + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return '\0'; + ssize_t n = read(fd, buf, sizeof(buf) - 1); + close(fd); + if (n <= 0) return '\0'; + buf[n] = '\0'; + const char *rparen = strrchr(buf, ')'); + if (!rparen || rparen[1] != ' ' || !rparen[2]) return '\0'; + return rparen[2]; +} + +static int handle_media_transport(const char *action) { + const char *mpv_json = NULL; + const char *osd_msg = NULL; + + if (strcmp(action, "play-pause") == 0) { + mpv_json = "{\"command\":[\"cycle\",\"pause\"]}\n"; + osd_msg = "Media: Play / Pause"; + } else if (strcmp(action, "prev") == 0) { + mpv_json = "{\"command\":[\"playlist-prev\",\"weak\"]}\n"; + osd_msg = "Media: Previous"; + } else if (strcmp(action, "next") == 0) { + mpv_json = "{\"command\":[\"playlist-next\",\"weak\"]}\n"; + osd_msg = "Media: Next"; + } else if (strcmp(action, "stop") == 0) { + mpv_json = "{\"command\":[\"quit\"]}\n"; + osd_msg = "Media: Stopped"; + } else { + return 1; + } + + if (send_mpv_ipc(mpv_json)) { + show_osd("osd", 1400, -1, osd_msg, NULL); + return 0; + } + + /* Fallback to console audio players (openmpt123 / mpg123) owned by current UID */ + DIR *d = opendir("/proc"); + if (!d) return 0; + uid_t me = getuid(); + bool acted = false; + bool resumed = false; + bool paused = false; + struct dirent *de; + + while ((de = readdir(d)) != NULL) { + if (!isdigit((unsigned char)de->d_name[0])) continue; + char path[280]; + struct stat st; + snprintf(path, sizeof(path), "/proc/%s", de->d_name); + if (stat(path, &st) != 0 || st.st_uid != me) continue; + snprintf(path, sizeof(path), "/proc/%s/comm", de->d_name); + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) continue; + char comm[64]; + ssize_t n = read(fd, comm, sizeof(comm) - 1); + close(fd); + if (n <= 0) continue; + comm[n] = '\0'; + while (n > 0 && (comm[n - 1] == '\n' || comm[n - 1] == '\r')) comm[--n] = '\0'; + if (strcmp(comm, "openmpt123") != 0 && strcmp(comm, "mpg123") != 0) continue; + + pid_t pid = (pid_t)strtol(de->d_name, NULL, 10); + if (pid <= 1) continue; + + if (strcmp(action, "play-pause") == 0) { + char state = read_proc_state(de->d_name); + if (state == 'T') { + kill(pid, SIGCONT); + resumed = true; + } else { + kill(pid, SIGSTOP); + paused = true; + } + acted = true; + } else if (strcmp(action, "next") == 0) { + kill(pid, SIGINT); + acted = true; + } else if (strcmp(action, "stop") == 0) { + kill(pid, SIGTERM); + acted = true; + } + } + closedir(d); + + if (acted) { + if (strcmp(action, "play-pause") == 0) { + show_osd("osd", 1400, -1, resumed ? "Media: Resumed" : (paused ? "Media: Paused" : osd_msg), NULL); + } else { + show_osd("osd", 1400, -1, osd_msg, NULL); + } + } + return 0; +} + +int main(int argc, char **argv) { + if (argc < 2) { + fprintf(stderr, "Usage: %s \n", + argv[0]); + return 1; + } + + const char *act = argv[1]; + if (strcmp(act, "bri-up") == 0) return handle_brightness(true); + if (strcmp(act, "bri-down") == 0) return handle_brightness(false); + if (strcmp(act, "vol-up") == 0 || strcmp(act, "vol-down") == 0 || + strcmp(act, "vol-mute") == 0 || strcmp(act, "mic-mute") == 0) { + return handle_audio(act); + } + if (strcmp(act, "screenshot") == 0) return handle_screenshot(false); + if (strcmp(act, "screenshot-window") == 0) return handle_screenshot(true); + if (strcmp(act, "play-pause") == 0 || strcmp(act, "prev") == 0 || + strcmp(act, "next") == 0 || strcmp(act, "stop") == 0) { + return handle_media_transport(act); + } + + fprintf(stderr, "geminux-media-key: unknown action '%s'\n", act); + return 1; +} diff --git a/src/geminux-daemons/geminux-power-policy.c b/src/geminux-daemons/geminux-power-policy.c index c0c210b..5318b18 100644 --- a/src/geminux-daemons/geminux-power-policy.c +++ b/src/geminux-daemons/geminux-power-policy.c @@ -40,13 +40,15 @@ geminux_profile_params_t geminux_policy_params(geminux_profile_t prof, bool on_a geminux_profile_params_t out; out.governor = "schedutil"; if (prof == POWER_PROFILE_ECO) { + out.governor = "schedutil"; out.a72_online = false; - out.a53_ll_max_khz = 624000UL; - out.a53_max_khz = 832000UL; + out.a53_ll_max_khz = 715000UL; + out.a53_max_khz = 962000UL; out.a72_max_khz = 0UL; out.dim_timeout_s = on_ac ? 180 : 60; out.suspend_timeout_s = on_ac ? 0 : 180; } else if (prof == POWER_PROFILE_PERFORMANCE) { + out.governor = "performance"; out.a72_online = true; out.a53_ll_max_khz = 1547000UL; out.a53_max_khz = 1846000UL; @@ -54,9 +56,10 @@ geminux_profile_params_t geminux_policy_params(geminux_profile_t prof, bool on_a out.dim_timeout_s = on_ac ? 600 : 180; out.suspend_timeout_s = 0; } else { + out.governor = "schedutil"; out.a72_online = true; - out.a53_ll_max_khz = on_ac ? 897000UL : 806000UL; - out.a53_max_khz = on_ac ? 1209000UL : 1092000UL; + out.a53_ll_max_khz = on_ac ? 1547000UL : 897000UL; + out.a53_max_khz = on_ac ? 1846000UL : 1209000UL; out.a72_max_khz = 2002000UL; out.dim_timeout_s = on_ac ? 300 : 120; out.suspend_timeout_s = on_ac ? 0 : 300; @@ -140,3 +143,62 @@ bool geminux_should_suspend_on_lid(const geminux_power_policy_t *p) { if (p->on_ac_power && p->inhibit_ac_lid) return false; return true; } + +static bool geminux_fg_r_valid(uint32_t r_uohm) { + return r_uohm >= 50000U && r_uohm <= 1500000U; +} + +static bool geminux_fg_full_valid(uint32_t full_uah) { + return full_uah >= 1000000U && full_uah <= 10000000U; +} + +bool geminux_fg_state_parse(const char *text, uint32_t *r_uohm, uint32_t *full_uah) { + if (!text || !r_uohm || !full_uah) return false; + uint32_t r = 0, full = 0; + bool got_r = false, got_full = false; + const char *p = text; + while (*p) { + const char *nl = strchr(p, '\n'); + size_t len = nl ? (size_t)(nl - p) : strlen(p); + size_t start = 0; + while (start < len && (p[start] == ' ' || p[start] == '\t')) { + start++; + } + while (len > start && (p[len - 1] == '\r' || p[len - 1] == ' ' || p[len - 1] == '\t')) { + len--; + } + size_t trim_len = len - start; + if (trim_len > 0 && trim_len < 96) { + char line[96]; + memcpy(line, p + start, trim_len); + line[trim_len] = '\0'; + unsigned long long val = 0; + char tail = '\0'; + if (sscanf(line, "learned_resistance_uohm=%llu%c", &val, &tail) == 1 && + val <= 0xffffffffULL) { + r = (uint32_t)val; + got_r = true; + } else if (sscanf(line, "learned_full_uah=%llu%c", &val, &tail) == 1 && + val <= 0xffffffffULL) { + full = (uint32_t)val; + got_full = true; + } + } + p = nl ? (nl + 1) : (p + strlen(p)); + } + if (!got_r || !got_full || !geminux_fg_r_valid(r) || !geminux_fg_full_valid(full)) { + return false; + } + *r_uohm = r; + *full_uah = full; + return true; +} + +int geminux_fg_state_format(uint32_t r_uohm, uint32_t full_uah, char *buf, size_t sz) { + if (!buf || sz == 0 || !geminux_fg_r_valid(r_uohm) || !geminux_fg_full_valid(full_uah)) { + return -1; + } + int n = snprintf(buf, sz, "learned_resistance_uohm=%u\nlearned_full_uah=%u\n", + r_uohm, full_uah); + return (n > 0 && (size_t)n < sz) ? 0 : -1; +} diff --git a/src/geminux-daemons/geminux-power-policy.h b/src/geminux-daemons/geminux-power-policy.h index f530084..12aa49c 100644 --- a/src/geminux-daemons/geminux-power-policy.h +++ b/src/geminux-daemons/geminux-power-policy.h @@ -60,6 +60,8 @@ geminux_idle_action_t geminux_policy_eval_idle( bool geminux_policy_add_inhibit(geminux_power_policy_t *p, const char *tag); bool geminux_policy_del_inhibit(geminux_power_policy_t *p, const char *tag); bool geminux_should_suspend_on_lid(const geminux_power_policy_t *p); +bool geminux_fg_state_parse(const char *text, uint32_t *r_uohm, uint32_t *full_uah); +int geminux_fg_state_format(uint32_t r_uohm, uint32_t full_uah, char *buf, size_t sz); static inline bool geminux_uevent_has_subsystem(const char *buf, size_t len, const char *subsys) { if (!buf || len == 0 || !subsys || !subsys[0]) return false; diff --git a/src/geminux-daemons/geminux-powerd.c b/src/geminux-daemons/geminux-powerd.c index 87e9ea5..82fede4 100644 --- a/src/geminux-daemons/geminux-powerd.c +++ b/src/geminux-daemons/geminux-powerd.c @@ -27,6 +27,9 @@ #define SOCK_PATH "/run/geminux/powerd.sock" #define PROFILE_FILE "/run/geminux/power-profile" +#define FG_STATE_DIR "/var/lib/geminux" +#define FG_STATE_FILE "/var/lib/geminux/fuel-gauge.state" +#define FG_SYSFS_DIR "/sys/class/power_supply/battery/device" #define MAX_EVDEVS 16 typedef struct { @@ -42,11 +45,16 @@ typedef struct { geminux_idle_stage_t idle_stage; geminux_power_policy_t policy; bool charge_thresh_set; + bool fg_restored; + bool fg_file_synced; + uint32_t saved_fg_r_uohm; + uint32_t saved_fg_full_uah; bool policy_applied; geminux_profile_t applied_profile; bool applied_ac; bool applied_a72_ready; bool applied_cpufreq_present; + bool applied_interactive_boost; pid_t consys_restore_pid; bool consys_suspended; bool bt_was_loaded; @@ -89,6 +97,91 @@ static void ensure_run_dir(void) { if (gr) chown("/run/geminux", 0, gr->gr_gid); } +static int read_sysfs_u32(const char *path, uint32_t *out) { + char buf[48] = {0}; + if (read_sysfs_line(path, buf, sizeof(buf)) != 0 || !buf[0]) return -1; + char *end = NULL; + errno = 0; + unsigned long long v = strtoull(buf, &end, 10); + if (errno != 0 || end == buf || *end != '\0' || v > 0xffffffffULL) return -1; + *out = (uint32_t)v; + return 0; +} + +static void restore_fuel_gauge_state(powerd_ctx_t *ctx) { + const char *r_path = FG_SYSFS_DIR "/learned_resistance_uohm"; + const char *f_path = FG_SYSFS_DIR "/learned_full_uah"; + if (access(r_path, F_OK) != 0 || access(f_path, F_OK) != 0) return; + + FILE *f = fopen(FG_STATE_FILE, "r"); + if (f) { + char buf[256] = {0}; + size_t n = fread(buf, 1, sizeof(buf) - 1, f); + fclose(f); + buf[n] = '\0'; + uint32_t r_val = 0, f_val = 0; + if (geminux_fg_state_parse(buf, &r_val, &f_val)) { + char r_str[32], f_str[32]; + snprintf(r_str, sizeof(r_str), "%u", r_val); + snprintf(f_str, sizeof(f_str), "%u", f_val); + write_sysfs_str(r_path, r_str); + write_sysfs_str(f_path, f_str); + ctx->fg_file_synced = true; + } + } + + uint32_t cur_r = 0, cur_f = 0; + if (read_sysfs_u32(r_path, &cur_r) == 0 && read_sysfs_u32(f_path, &cur_f) == 0) { + ctx->saved_fg_r_uohm = cur_r; + ctx->saved_fg_full_uah = cur_f; + } + ctx->fg_restored = true; +} + +static void save_fuel_gauge_state(powerd_ctx_t *ctx) { + uint32_t r_val = 0, f_val = 0; + if (read_sysfs_u32(FG_SYSFS_DIR "/learned_resistance_uohm", &r_val) != 0 || + read_sysfs_u32(FG_SYSFS_DIR "/learned_full_uah", &f_val) != 0) { + return; + } + char content[128]; + if (geminux_fg_state_format(r_val, f_val, content, sizeof(content)) != 0) return; + if (ctx->fg_file_synced && + r_val == ctx->saved_fg_r_uohm && + f_val == ctx->saved_fg_full_uah) { + return; + } + + mkdir("/var/lib", 0755); + mkdir(FG_STATE_DIR, 0755); + char tmp_path[128]; + snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", FG_STATE_FILE); + int fd = open(tmp_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (fd < 0) return; + + size_t len = strlen(content), off = 0; + bool ok = true; + while (off < len) { + ssize_t w = write(fd, content + off, len - off); + if (w <= 0) { + if (w < 0 && errno == EINTR) continue; + ok = false; + break; + } + off += (size_t)w; + } + if (ok && fsync(fd) != 0) ok = false; + if (close(fd) != 0) ok = false; + + if (ok && rename(tmp_path, FG_STATE_FILE) == 0) { + ctx->saved_fg_r_uohm = r_val; + ctx->saved_fg_full_uah = f_val; + ctx->fg_file_synced = true; + } else { + unlink(tmp_path); + } +} + static void refresh_ac_and_hdmi(powerd_ctx_t *ctx) { if (!ctx->charge_thresh_set) { if (write_sysfs_str("/sys/class/power_supply/battery/charge_control_end_threshold", "100") == 0) { @@ -156,6 +249,9 @@ static void toggle_backlight(powerd_ctx_t *ctx, bool on) { save_active_brightness(ctx, p); write_sysfs_str(p, "0"); } else { + char pwr[320]; + snprintf(pwr, sizeof(pwr), "/sys/class/backlight/%s/bl_power", de->d_name); + write_sysfs_str(pwr, "0"); char restore[32]; int val = ctx->saved_brightness > 0 ? ctx->saved_brightness : 128; snprintf(restore, sizeof(restore), "%d", val); @@ -217,11 +313,13 @@ static void evaluate_idle(powerd_ctx_t *ctx) { if (act == IDLE_ACT_DIM) { dim_backlight(ctx); ctx->idle_stage = IDLE_STAGE_DIMMED; + apply_cpu_sysfs(ctx, false); arm_timer_ms(ctx->tmr_fd, next_wait_ms); } else if (act == IDLE_ACT_LOCK_BLANK) { lock_x11_session(); toggle_backlight(ctx, false); ctx->idle_stage = IDLE_STAGE_LOCKED_BLANK; + apply_cpu_sysfs(ctx, false); arm_timer_ms(ctx->tmr_fd, 0); } else if (act == IDLE_ACT_SUSPEND) { arm_timer_ms(ctx->tmr_fd, 0); @@ -236,6 +334,7 @@ static void note_user_activity(powerd_ctx_t *ctx) { if (ctx->idle_stage != IDLE_STAGE_ACTIVE) { ctx->idle_stage = IDLE_STAGE_ACTIVE; toggle_backlight(ctx, true); + apply_cpu_sysfs(ctx, false); evaluate_idle(ctx); } } @@ -243,11 +342,15 @@ static void note_user_activity(powerd_ctx_t *ctx) { static void apply_cpu_sysfs(powerd_ctx_t *ctx, bool force) { bool a72_ready = (access("/sys/module/mt6797_a72", F_OK) == 0); bool cpufreq_present = (access("/sys/devices/system/cpu/cpufreq/policy0", F_OK) == 0); + bool interactive_boost = (ctx->policy.profile == POWER_PROFILE_BALANCED && + ctx->idle_stage == IDLE_STAGE_ACTIVE && + !ctx->policy.lid_closed); if (!force && ctx->policy_applied && ctx->applied_profile == ctx->policy.profile && ctx->applied_ac == ctx->policy.on_ac_power && ctx->applied_a72_ready == a72_ready && - ctx->applied_cpufreq_present == cpufreq_present) { + ctx->applied_cpufreq_present == cpufreq_present && + ctx->applied_interactive_boost == interactive_boost) { return; } @@ -266,17 +369,35 @@ static void apply_cpu_sysfs(powerd_ctx_t *ctx, bool force) { struct dirent *de; while ((de = readdir(d)) != NULL) { if (strncmp(de->d_name, "policy", 6) != 0) continue; - char p[256], freq_buf[32]; + char p[256], freq_buf[32], min_buf[32] = "221000", max_hw_buf[32] = {0}; + int first_cpu = atoi(de->d_name + 6); + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/cpuinfo_min_freq", de->d_name); + (void)read_sysfs_line(p, min_buf, sizeof(min_buf)); + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/cpuinfo_max_freq", de->d_name); + unsigned long hw_max = + (read_sysfs_line(p, max_hw_buf, sizeof(max_hw_buf)) == 0) ? strtoul(max_hw_buf, NULL, 10) : 0UL; + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_governor", de->d_name); write_sysfs_str(p, par.governor); - int first_cpu = atoi(de->d_name + 6); unsigned long cap = (first_cpu >= 8) ? par.a72_max_khz : (first_cpu >= 4) ? par.a53_max_khz : par.a53_ll_max_khz; + if (hw_max > 0 && (cap == 0 || cap > hw_max)) { + cap = hw_max; + } + + /* Reset floor before adjusting ceiling so scaling_min_freq never blocks scaling_max_freq. */ + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_min_freq", de->d_name); + write_sysfs_str(p, min_buf); + if (cap > 0) { snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_max_freq", de->d_name); snprintf(freq_buf, sizeof(freq_buf), "%lu", cap); write_sysfs_str(p, freq_buf); + if (interactive_boost && first_cpu < 8) { + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_min_freq", de->d_name); + write_sysfs_str(p, freq_buf); + } } } closedir(d); @@ -292,6 +413,7 @@ static void apply_cpu_sysfs(powerd_ctx_t *ctx, bool force) { ctx->applied_ac = ctx->policy.on_ac_power; ctx->applied_a72_ready = a72_ready; ctx->applied_cpufreq_present = cpufreq_present; + ctx->applied_interactive_boost = interactive_boost; } static void apply_cpu_policy(powerd_ctx_t *ctx, bool force) { @@ -542,15 +664,93 @@ static void refresh_lid_state(powerd_ctx_t *ctx) { } } +/* gpio-keys SW_LID applies a 64 ms debounce timer on wakeup; wait up to + * timeout_ms using poll() so a lid-open wake sees SW_LID == 0 before we + * decide whether to light the backlight. */ +static void wait_post_resume_lid_events(powerd_ctx_t *ctx, int timeout_ms) { + refresh_lid_state(ctx); + if (!ctx->policy.lid_closed || ctx->num_ev <= 0) return; + + uint64_t deadline = monotonic_ms() + (uint64_t)timeout_ms; + struct pollfd pfds[MAX_EVDEVS]; + while (ctx->policy.lid_closed) { + uint64_t now = monotonic_ms(); + if (now >= deadline) break; + int slice = (int)(deadline - now); + if (slice > 20) slice = 20; + + for (int i = 0; i < ctx->num_ev; i++) { + pfds[i].fd = ctx->ev_fds[i]; + pfds[i].events = POLLIN; + pfds[i].revents = 0; + } + int pr = poll(pfds, (nfds_t)ctx->num_ev, slice); + if (pr < 0) { + if (errno == EINTR) continue; + break; + } + for (int i = 0; i < ctx->num_ev; i++) { + if (!(pfds[i].revents & POLLIN)) continue; + struct input_event iev; + while (read(ctx->ev_fds[i], &iev, sizeof(iev)) == (ssize_t)sizeof(iev)) { + if (iev.type == EV_SW && iev.code == SW_LID) { + ctx->policy.lid_closed = (iev.value != 0); + } else if (iev.type == EV_KEY || iev.type == EV_REL || iev.type == EV_ABS) { + ctx->last_input_ms = monotonic_ms(); + } + } + } + refresh_lid_state(ctx); + } +} + +static void prepare_cpus_for_suspend(void) { + DIR *d = opendir("/sys/devices/system/cpu/cpufreq"); + if (d) { + struct dirent *de; + while ((de = readdir(d)) != NULL) { + if (strncmp(de->d_name, "policy", 6) != 0) continue; + char p[256], min_buf[32] = "221000"; + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/cpuinfo_min_freq", de->d_name); + (void)read_sysfs_line(p, min_buf, sizeof(min_buf)); + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_min_freq", de->d_name); + write_sysfs_str(p, min_buf); + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_governor", de->d_name); + write_sysfs_str(p, "powersave"); + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_max_freq", de->d_name); + write_sysfs_str(p, min_buf); + } + closedir(d); + } + for (int cpu = 9; cpu >= 1; cpu--) { + char p[128]; + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpu%d/online", cpu); + write_sysfs_str(p, "0"); + } +} + +static void restore_cpus_after_resume(powerd_ctx_t *ctx) { + for (int cpu = 1; cpu <= 7; cpu++) { + char p[128]; + snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpu%d/online", cpu); + write_sysfs_str(p, "1"); + } + ctx->policy_applied = false; +} + static void trigger_suspend(powerd_ctx_t *ctx) { + arm_timer_ms(ctx->tmr_fd, 0); lock_x11_session(); toggle_backlight(ctx, false); + save_fuel_gauge_state(ctx); prepare_consys_for_suspend(ctx); + prepare_cpus_for_suspend(); write_sysfs_str("/sys/power/mem_sleep", "deep"); bool suspended = (write_sysfs_str("/sys/power/state", "mem") == 0 || write_sysfs_str("/sys/power/state", "freeze") == 0); + restore_cpus_after_resume(ctx); restore_consys_after_resume(ctx); - refresh_lid_state(ctx); + wait_post_resume_lid_events(ctx, 90); refresh_ac_and_hdmi(ctx); if (suspended && !ctx->policy.lid_closed) { ctx->idle_stage = IDLE_STAGE_ACTIVE; @@ -707,6 +907,7 @@ int main(void) { ctx.last_input_ms = monotonic_ms(); ctx.idle_stage = IDLE_STAGE_ACTIVE; + restore_fuel_gauge_state(&ctx); refresh_ac_and_hdmi(&ctx); scan_input_devices(&ctx); apply_cpu_policy(&ctx, true); @@ -747,17 +948,27 @@ int main(void) { char ubuf[2048]; ssize_t ur; bool need_ev_rescan = false; + bool need_ps = false; bool need_ps_or_drm = false; while ((ur = recv(ctx.uev_fd, ubuf, sizeof(ubuf), 0)) > 0) { if (geminux_uevent_has_subsystem(ubuf, (size_t)ur, "input")) { need_ev_rescan = true; } - if (geminux_uevent_has_subsystem(ubuf, (size_t)ur, "power_supply") || - geminux_uevent_has_subsystem(ubuf, (size_t)ur, "drm")) { + if (geminux_uevent_has_subsystem(ubuf, (size_t)ur, "power_supply")) { + need_ps = true; + need_ps_or_drm = true; + } else if (geminux_uevent_has_subsystem(ubuf, (size_t)ur, "drm")) { need_ps_or_drm = true; } } if (need_ev_rescan) scan_input_devices(&ctx); + if (need_ps) { + if (!ctx.fg_restored) { + restore_fuel_gauge_state(&ctx); + } else { + save_fuel_gauge_state(&ctx); + } + } if (need_ps_or_drm) { bool prev_ac = ctx.policy.on_ac_power; bool prev_hdmi = ctx.policy.hdmi_connected; @@ -810,6 +1021,7 @@ int main(void) { } } + save_fuel_gauge_state(&ctx); unlink(SOCK_PATH); close(ctx.epfd); return 0; diff --git a/src/libgemui/gemui.c b/src/libgemui/gemui.c index 7d6951f..ab3167e 100644 --- a/src/libgemui/gemui.c +++ b/src/libgemui/gemui.c @@ -35,6 +35,10 @@ struct gemui_app { Window root; Window win; Pixmap backbuf; + cairo_surface_t *img_surf; + cairo_t *img_cr; + cairo_surface_t *xlib_surf; + PangoLayout *pango_layout; GC gc; int bw; int bh; @@ -71,6 +75,7 @@ struct gemui_app { }; static int g_sig_pipe[2] = {-1, -1}; +static PangoLayout *g_active_layout = NULL; static void gemui_sigusr1_handler(int sig) { (void)sig; @@ -292,7 +297,26 @@ void gemui_theme_reload(gemui_app_t *app) { static void gemui_ensure_backbuf(gemui_app_t *app) { if (app->w <= 0 || app->h <= 0) return; - if (app->backbuf && app->bw == app->w && app->bh == app->h) return; + if (app->backbuf && app->img_cr && app->xlib_surf && + app->bw == app->w && app->bh == app->h) { + return; + } + if (app->pango_layout) { + g_object_unref(app->pango_layout); + app->pango_layout = NULL; + } + if (app->img_cr) { + cairo_destroy(app->img_cr); + app->img_cr = NULL; + } + if (app->img_surf) { + cairo_surface_destroy(app->img_surf); + app->img_surf = NULL; + } + if (app->xlib_surf) { + cairo_surface_destroy(app->xlib_surf); + app->xlib_surf = NULL; + } if (app->backbuf) { XFreePixmap(app->dpy, app->backbuf); app->backbuf = 0; @@ -300,8 +324,17 @@ static void gemui_ensure_backbuf(gemui_app_t *app) { app->backbuf = XCreatePixmap(app->dpy, app->win, (unsigned int)app->w, (unsigned int)app->h, (unsigned int)DefaultDepth(app->dpy, app->screen)); + app->xlib_surf = cairo_xlib_surface_create(app->dpy, app->backbuf, + DefaultVisual(app->dpy, app->screen), + app->w, app->h); + app->img_surf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, app->w, app->h); + app->img_cr = cairo_create(app->img_surf); + app->pango_layout = pango_cairo_create_layout(app->img_cr); app->bw = app->w; app->bh = app->h; + if (app->backbuf) { + XSetWindowBackgroundPixmap(app->dpy, app->win, app->backbuf); + } } static int gemui_ignore_xerror(Display *dpy, XErrorEvent *ev) { @@ -360,11 +393,16 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, app->w = w; app->h = h; + int wx = fullscreen_override ? 0 : (sw - w) / 2; + int wy = fullscreen_override ? 0 : (sh - h) / 2; + if (wx < 0) wx = 0; + if (wy < 0) wy = 0; + gemui_theme_reload(app); XSetWindowAttributes swa; memset(&swa, 0, sizeof(swa)); - swa.background_pixel = BlackPixel(dpy, app->screen); + swa.background_pixmap = None; swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask | FocusChangeMask; @@ -372,9 +410,21 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, swa.override_redirect = True; } - unsigned long mask = CWBackPixel | CWEventMask | (fullscreen_override ? CWOverrideRedirect : 0); - app->win = XCreateWindow(dpy, app->root, 0, 0, (unsigned int)w, (unsigned int)h, 0, + unsigned long mask = CWBackPixmap | CWEventMask | (fullscreen_override ? CWOverrideRedirect : 0); + app->win = XCreateWindow(dpy, app->root, wx, wy, (unsigned int)w, (unsigned int)h, 0, CopyFromParent, InputOutput, CopyFromParent, mask, &swa); + { + XSizeHints *shints = XAllocSizeHints(); + if (shints) { + shints->flags = PPosition | PSize; + shints->x = wx; + shints->y = wy; + shints->width = w; + shints->height = h; + XSetWMNormalHints(dpy, app->win, shints); + XFree(shints); + } + } { Cursor cur = XCreateFontCursor(dpy, XC_left_ptr); if (cur != None) { @@ -412,8 +462,9 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, XNClientWindow, app->win, XNFocusWindow, app->win, NULL); } - XMapRaised(dpy, app->win); if (fullscreen_override) { + XMapRaised(dpy, app->win); + app->mapped = true; XMoveResizeWindow(dpy, app->win, 0, 0, (unsigned int)sw, (unsigned int)sh); gemui_save_prev_focus(app); XSetInputFocus(dpy, app->win, RevertToPointerRoot, CurrentTime); @@ -428,6 +479,10 @@ void gemui_destroy(gemui_app_t *app) { gemui_restore_prev_focus(app); if (app->xic) XDestroyIC(app->xic); if (app->xim) XCloseIM(app->xim); + if (app->pango_layout) g_object_unref(app->pango_layout); + if (app->img_cr) cairo_destroy(app->img_cr); + if (app->img_surf) cairo_surface_destroy(app->img_surf); + if (app->xlib_surf) cairo_surface_destroy(app->xlib_surf); if (app->backbuf) XFreePixmap(app->dpy, app->backbuf); if (app->gc) XFreeGC(app->dpy, app->gc); if (app->win) XDestroyWindow(app->dpy, app->win); @@ -518,13 +573,18 @@ void gemui_quit(gemui_app_t *app, int code) { bool gemui_grab_input(gemui_app_t *app) { if (!app) return false; + if (!app->mapped) { + gemui_flush_draw(app); + } bool ok_kbd = XGrabKeyboard(app->dpy, app->win, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess; XGrabPointer(app->dpy, app->win, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, app->win, None, CurrentTime); gemui_save_prev_focus(app); - XSetInputFocus(app->dpy, app->win, RevertToPointerRoot, CurrentTime); + if (app->mapped) { + XSetInputFocus(app->dpy, app->win, RevertToPointerRoot, CurrentTime); + } XFlush(app->dpy); return ok_kbd; } @@ -563,23 +623,31 @@ const gemui_hit_t *gemui_hit_test(const gemui_app_t *app, int x, int y) { static void gemui_render_frame(gemui_app_t *app) { if (!app || !app->need_redraw || app->w <= 0 || app->h <= 0) return; gemui_ensure_backbuf(app); - if (!app->backbuf) return; - - cairo_surface_t *surf = cairo_xlib_surface_create( - app->dpy, app->backbuf, DefaultVisual(app->dpy, app->screen), app->w, app->h); - cairo_t *cr = cairo_create(surf); + if (!app->backbuf || !app->img_cr || !app->xlib_surf) return; + cairo_t *cr = app->img_cr; + g_active_layout = app->pango_layout; gemui_hits_clear(app); gemui_fill_rect(cr, (gemui_rect_t){0, 0, app->w, app->h}, app->theme.bg_main); if (app->handlers.on_draw) { app->handlers.on_draw(app, cr, app->w, app->h, app->userdata); } gemui_draw_toast(app, cr); + g_active_layout = NULL; + cairo_surface_flush(app->img_surf); - cairo_destroy(cr); - cairo_surface_flush(surf); - cairo_surface_destroy(surf); + cairo_t *xcr = cairo_create(app->xlib_surf); + cairo_set_operator(xcr, CAIRO_OPERATOR_SOURCE); + cairo_set_source_surface(xcr, app->img_surf, 0, 0); + cairo_paint(xcr); + cairo_destroy(xcr); + cairo_surface_flush(app->xlib_surf); + if (!app->mapped) { + XSetWindowBackgroundPixmap(app->dpy, app->win, app->backbuf); + XMapRaised(app->dpy, app->win); + app->mapped = true; + } XCopyArea(app->dpy, app->backbuf, app->win, app->gc, 0, 0, (unsigned int)app->w, (unsigned int)app->h, 0, 0); XFlush(app->dpy); @@ -658,6 +726,12 @@ static void gemui_handle_x_events(gemui_app_t *app) { } break; case MotionNotify: + while (XPending(app->dpy) > 0) { + XEvent pev; + XPeekEvent(app->dpy, &pev); + if (pev.type != MotionNotify || pev.xmotion.window != ev.xmotion.window) break; + XNextEvent(app->dpy, &ev); + } if (app->ptr_down && app->handlers.on_ptr) { app->handlers.on_ptr(app, GEMUI_PTR_MOVE, ev.xmotion.x, ev.xmotion.y, 0, app->userdata); @@ -807,13 +881,14 @@ static int gemui_draw_pango(cairo_t *cr, const char *face, int px_size, gemui_rect_t r, const char *text, bool bold, int align, gemui_color_t c) { if (!text || !text[0] || r.w <= 4 || r.h <= 4) return 0; - PangoLayout *layout = pango_cairo_create_layout(cr); + PangoLayout *layout = g_active_layout ? g_active_layout : pango_cairo_create_layout(cr); char desc_str[160]; snprintf(desc_str, sizeof(desc_str), "%s%s %dpx", face && face[0] ? face : "Fira Code", bold ? " Bold" : "", px_size > 8 ? px_size : 14); PangoFontDescription *desc = pango_font_description_from_string(desc_str); + pango_layout_set_attributes(layout, NULL); pango_layout_set_font_description(layout, desc); pango_layout_set_width(layout, r.w * PANGO_SCALE); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END); @@ -835,7 +910,7 @@ static int gemui_draw_pango(cairo_t *cr, const char *face, int px_size, pango_cairo_show_layout(cr, layout); pango_font_description_free(desc); - g_object_unref(layout); + if (!g_active_layout) g_object_unref(layout); return tw; }