diff --git a/API.md b/API.md index 119b30125..f76f28295 100644 --- a/API.md +++ b/API.md @@ -234,14 +234,13 @@ impl Drop for MyServer { } // reference counting implementation for servers that can be cloned or have multiple instances in a thread -//REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); +//REFCOUNT.fetch_add(1, Ordering::Relaxed); use core::sync::atomic::{AtomicU32, Ordering}; static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for Codec { fn drop(&mut self) { // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/Cargo.lock b/Cargo.lock index a961c4890..7483f098b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -477,7 +477,7 @@ dependencies = [ [[package]] name = "com_rs" version = "0.1.0" -source = "git+https://github.com/betrusted-io/com_rs.git?rev=f7c46612a4181e3d33ec6c5fc90740062d2d9832#f7c46612a4181e3d33ec6c5fc90740062d2d9832" +source = "git+https://github.com/betrusted-io/com_rs.git?rev=5e3c741369ae2c1a537b41b70bdfd40d1b62e06d#5e3c741369ae2c1a537b41b70bdfd40d1b62e06d" [[package]] name = "com_rs-ref" diff --git a/apps/ball/locales/i18n.json b/apps/ball/locales/i18n.json index 47ead47fd..d52c3b244 100644 --- a/apps/ball/locales/i18n.json +++ b/apps/ball/locales/i18n.json @@ -1,26 +1,31 @@ { "ballapp.notification_a": { "en": "Bouncing ball ⛹ demo.\nInterrupted with key hit: ", + "ja": "弾むボール ⛹ デモ。キーヒットで中断: ", "zh": "弹跳球演示.⛹\n因击键而中断:", "en-audio": "Bouncing ball demo. Interrupted with key hit:" }, "ballapp.notification_b": { "en": "Press any key to continue.", + "ja": "続行するには何かキーを押してください。", "zh": "按任意键继续", "en-audio": "Press any key to continue." }, "ballapp.mode_prompt": { "en": "Pick a mode of operation:", + "ja": "動作モードを選択してください:", "zh": "选择一种操作模式:", "en-audio": "Pick a mode of operation:" }, "ballapp.random": { "en": "Random", + "ja": "ランダム", "zh": "随机的", "en-audio": "Random" }, "ballapp.tilt": { "en": "Tilt", + "ja": "傾ける", "zh": "加速度计倾斜", "en-audio": "Tilt" } diff --git a/apps/repl/locales/i18n.json b/apps/repl/locales/i18n.json index 2276ea502..7158dff63 100644 --- a/apps/repl/locales/i18n.json +++ b/apps/repl/locales/i18n.json @@ -1,26 +1,31 @@ { "replapp.greeting": { "en": "Welcome to the simple REPL demo.", + "ja": "シンプルなREPLデモへようこそ", "zh": "简单的 repl 演示活动", "en-audio": "Welcome to the simple REPL demo." }, "replapp.audio.start": { "en": "tone started...", + "ja": "トーン開始…", "zh": "哔声开始...", "en-audio": "tone started..." }, "replapp.audio.help": { "en": "audio [tone [freq [duration]]]", + "ja": "オーディオ [ トーン [ 周波数 [ 間隔 ]]]", "zh": "audio [tone [音频 [时长]]]", "en-audio": "audio tone, then optional frequency plus optional duration." }, "replapp.audio.completion_a": { "en": "Playback stopped at", + "ja": "再生停止位置: ", "zh": "播放停止在", "en-audio": "Playback stopped at" }, "replapp.audio.completion_b": { "en": "frames", + "ja": "フレーム", "zh": "帧", "en-audio": "frames" } diff --git a/imports/com_rs-ref/Cargo.toml b/imports/com_rs-ref/Cargo.toml index 4a1be6c2c..e76e51981 100644 --- a/imports/com_rs-ref/Cargo.toml +++ b/imports/com_rs-ref/Cargo.toml @@ -7,7 +7,7 @@ description = "com_rs import package" # Dependency policy: fully specify dependencies to the minor version number [dependencies] -com_rs = { git = "https://github.com/betrusted-io/com_rs.git", rev = "f7c46612a4181e3d33ec6c5fc90740062d2d9832" } +com_rs = { git = "https://github.com/betrusted-io/com_rs.git", rev = "5e3c741369ae2c1a537b41b70bdfd40d1b62e06d" } #com_rs = { path = "../../../betrusted-ec/sw/com_rs" } diff --git a/services/codec/src/lib.rs b/services/codec/src/lib.rs index 7f66d91f1..75850ef5a 100644 --- a/services/codec/src/lib.rs +++ b/services/codec/src/lib.rs @@ -15,7 +15,7 @@ pub struct Codec { } impl Codec { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_CODEC).expect("Can't connect to Codec server"); Ok(Codec { conn, @@ -131,8 +131,7 @@ static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for Codec { fn drop(&mut self) { // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/com/src/lib.rs b/services/com/src/lib.rs index 46785bab5..543809c93 100644 --- a/services/com/src/lib.rs +++ b/services/com/src/lib.rs @@ -49,7 +49,7 @@ pub struct Com { } impl Com { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_COM).expect("Can't connect to COM server"); Ok(Com { conn, @@ -635,8 +635,7 @@ impl Drop for Com { unsafe{xous::disconnect(cid).unwrap();} } // now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/com/src/main.rs b/services/com/src/main.rs index aa5936641..773c6b02c 100644 --- a/services/com/src/main.rs +++ b/services/com/src/main.rs @@ -421,6 +421,28 @@ fn xmain() -> ! { Some(Opcode::LinkReset) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { com.txrx(ComState::LINK_SYNC.verb); ticktimer.sleep_ms(200).unwrap(); // give some time for the link to reset - the EC does not have a guaranteed latency to respond to a link reset + let mut attempts = 0; + let ping_value = 0xaeedu16; // for various reasons, this is a string that is "unlikely" to happen randomly + loop { + com.txrx(ComState::LINK_PING.verb); + com.txrx(ping_value); + let pong = com.wait_txrx(ComState::LINK_READ.verb, Some(500)); + let phase = com.wait_txrx(ComState::LINK_READ.verb, Some(500)); + if pong == !ping_value && + phase == 0x600d { // 0x600d is a hard-coded constant. It's included to confirm that we aren't "wedged" just sending one value back at us + break; + } else { + log::warn!("Link reset: establishing link sync, attempt {} [{:04x}/{:04x}]", attempts, pong, phase); + com.txrx(ComState::LINK_SYNC.verb); + ticktimer.sleep_ms(200).unwrap(); + attempts += 1; + } + if attempts > 50 { + // abort and return failure + xous::return_scalar(msg.sender, 0).unwrap(); + continue; + } + } xous::return_scalar(msg.sender, 1).unwrap(); }), Some(Opcode::ReseedTrng) => xous::msg_scalar_unpack!(msg, _, _, _, _, { @@ -672,17 +694,20 @@ fn xmain() -> ! { com.txrx(ComState::WF200_RESET.verb); com.txrx(0); let mut attempts = 0; + let ping_value = 0xaeedu16; // for various reasons, this is a string that is "unlikely" to happen randomly loop { - com.txrx(ComState::LOOP_TEST.verb); - let ack = com.wait_txrx(ComState::LINK_READ.verb, Some(5000)); // should finish with 5 seconds - // TODO: offer a more robust sequence than 0x00 for detecting if sync is back... - if (ack & 0xff) != 0x00 { //it will read 0xdd or 0xff if the EC is actually still in reset or held up - log::warn!("Wf200 reset took too long, trying to re-establish link sync...{:x}", ack); + com.txrx(ComState::LINK_PING.verb); + com.txrx(ping_value); + let pong = com.wait_txrx(ComState::LINK_READ.verb, Some(5000)); // should finish with 5 seconds + let phase = com.wait_txrx(ComState::LINK_READ.verb, Some(500)); + if pong == !ping_value && + phase == 0x600d { // 0x600d is a hard-coded constant. It's included to confirm that we aren't "wedged" just sending one value back at us + break; + } else { + log::warn!("Wf200 reset: establishing link sync, attempt {} [{:04x}/{:04x}]", attempts, pong, phase); com.txrx(ComState::LINK_SYNC.verb); ticktimer.sleep_ms(200).unwrap(); attempts += 1; - } else { - break; } if attempts > 50 { // something has gone horribly wrong. Reset the EC entirely. diff --git a/services/dns/src/lib.rs b/services/dns/src/lib.rs index f9187ab8f..2d24f6257 100644 --- a/services/dns/src/lib.rs +++ b/services/dns/src/lib.rs @@ -15,7 +15,7 @@ pub struct Dns { } impl Dns { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_DNS).expect("Can't connect to Dns server"); Ok(Dns { conn @@ -55,8 +55,7 @@ impl Drop for Dns { // the connection to the server side must be reference counted, so that multiple instances of this object within // a single process do not end up de-allocating the CID on other threads before they go out of scope. // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), diff --git a/services/engine-25519/src/lib.rs b/services/engine-25519/src/lib.rs index fab252d5f..ff8f9c3c0 100644 --- a/services/engine-25519/src/lib.rs +++ b/services/engine-25519/src/lib.rs @@ -26,7 +26,7 @@ pub struct Engine25519 { impl Engine25519 { // this is used to set up a system with async callbacks pub fn new_async(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_ENGINE25519).expect("Can't connect to Engine25519 server"); let sid = xous::create_server().unwrap(); @@ -41,7 +41,7 @@ impl Engine25519 { } // typically, we just want synchronous callbacks. This integrates more nicely into single-threaded code. pub fn new() -> Self { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let xns = xous_names::XousNames::new().unwrap(); let conn = xns.request_connection_blocking(api::SERVER_NAME_ENGINE25519).expect("Can't connect to Engine25519 server"); @@ -149,8 +149,7 @@ static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for Engine25519 { fn drop(&mut self) { // disconnect from the main server, only if there are no more instances active - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } // disconnect and destroy the callback server that is specific to this instance diff --git a/services/gam/locales/i18n.json b/services/gam/locales/i18n.json index a6a3c3419..686824bbe 100644 --- a/services/gam/locales/i18n.json +++ b/services/gam/locales/i18n.json @@ -1,11 +1,13 @@ { "radio.select_and_close": { "en": "[ Okay ]", + "ja": "[ OK ]", "zh": "[ 确定 ]", "en-audio": "Accept and close radio box" }, "notification.dismiss": { "en": "[ Press any key ]", + "ja": "[ 何かのキーを押してください。]", "zh": "[ 按任意键 ]", "en-audio": "Press any key" } diff --git a/services/gam/src/lib.rs b/services/gam/src/lib.rs index fd7b88e2d..10aa2ab85 100644 --- a/services/gam/src/lib.rs +++ b/services/gam/src/lib.rs @@ -76,7 +76,7 @@ pub struct Gam { } impl Gam { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_GAM).expect("Can't connect to GAM"); Ok(Gam { conn, @@ -385,8 +385,7 @@ impl Drop for Gam { unsafe{xous::disconnect(cid).unwrap();} xous::destroy_server(sid).unwrap(); } - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/graphics-server/src/lib.rs b/services/graphics-server/src/lib.rs index 3628adedb..f7e6f3188 100644 --- a/services/graphics-server/src/lib.rs +++ b/services/graphics-server/src/lib.rs @@ -24,7 +24,7 @@ pub struct Gfx { } impl Gfx { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns .request_connection_blocking(api::SERVER_NAME_GFX) .expect("Can't connect to GFX"); @@ -266,8 +266,7 @@ static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for Gfx { fn drop(&mut self) { // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe { xous::disconnect(self.conn).unwrap(); } diff --git a/services/ime-frontend/locales/i18n.json b/services/ime-frontend/locales/i18n.json index ee0f61ea3..18bde3a0d 100644 --- a/services/ime-frontend/locales/i18n.json +++ b/services/ime-frontend/locales/i18n.json @@ -1,6 +1,7 @@ { "input.greeting": { "en": "Ready for input...", + "ja": "入力可能...", "zh": "等待输入...", "en-audio": "Ready for input" } diff --git a/services/ime-plugin-api/src/lib.rs b/services/ime-plugin-api/src/lib.rs index 6f4221ea4..965ce1a05 100644 --- a/services/ime-plugin-api/src/lib.rs +++ b/services/ime-plugin-api/src/lib.rs @@ -242,7 +242,7 @@ pub struct ImeFrontEnd { } impl ImeFrontEnd { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns .request_connection_blocking(SERVER_NAME_IME_FRONT) .expect("Can't connect to IMEF"); @@ -272,8 +272,7 @@ impl Drop for ImeFrontEnd { } xous::destroy_server(sid).unwrap(); } - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe { xous::disconnect(self.cid).unwrap(); } diff --git a/services/jtag/src/lib.rs b/services/jtag/src/lib.rs index f9a5a9a9a..232835181 100644 --- a/services/jtag/src/lib.rs +++ b/services/jtag/src/lib.rs @@ -12,7 +12,7 @@ pub struct Jtag { } impl Jtag { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_JTAG).expect("Can't connect to JTAG server"); Ok(Jtag { conn @@ -146,8 +146,7 @@ impl Drop for Jtag { // the connection to the server side must be reference counted, so that multiple instances of this object within // a single process do not end up de-allocating the CID on other threads before they go out of scope. // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), diff --git a/services/keyboard/src/lib.rs b/services/keyboard/src/lib.rs index 0e33148fd..3b69d8306 100644 --- a/services/keyboard/src/lib.rs +++ b/services/keyboard/src/lib.rs @@ -14,7 +14,7 @@ pub struct Keyboard { } impl Keyboard { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_KBD).expect("Can't connect to KBD"); Ok(Keyboard { conn, @@ -65,8 +65,7 @@ static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for Keyboard { fn drop(&mut self) { // now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/llio/locales/i18n.json b/services/llio/locales/i18n.json index b995a0903..467e788c7 100644 --- a/services/llio/locales/i18n.json +++ b/services/llio/locales/i18n.json @@ -1,81 +1,97 @@ { "rtc.month": { "en": "Enter month (1-12)", + "ja": "月(1-12)を入力してください。", "zh": "输入月份 (1-12)", "en-audio": "Enter month one through twelve" }, "rtc.day": { "en": "Enter day (1-31)", + "ja": "日数 (1-31) を入力してください。", "zh": "输入日期 (1-31)", "en-audio": "Enter day one through 31" }, "rtc.year": { "en": "Enter last two digits of year", + "ja": "西暦の下2桁を入力してください。", "zh": "输入年份 (最后两位数)", "en-audio": "Enter last two digits of year" }, "rtc.hour": { "en": "Enter hours (0-23)", + "ja": "時間(0-23)を入力してください。", "zh": "输入小时 (0-23)", "en-audio": "Enter hours as 24 hour format" }, "rtc.minute": { "en": "Enter minutes (0-59)", + "ja": "分(0-59)を入力してください。", "zh": "输入分钟 (0-59)", "en-audio": "Enter minutes" }, "rtc.seconds": { "en": "Enter seconds (0-59)", + "ja": "秒 (0-59) を入力してください。", "zh": "输入秒数 (0-59)", "en-audio": "Enter seconds" }, "rtc.day_of_week": { "en": "Select the day of week", + "ja": "曜日を選択してください。", "zh": "[星期几]清单框", "en-audio": "Select the day of week" }, "rtc.monday": { "en": "Monday", + "ja": "月曜日", "zh": "星期一", "en-audio": "Monday" }, "rtc.tuesday": { "en": "Tuesday", + "ja": "火曜日", "zh": "星期二", "en-audio": "Tuesday" }, "rtc.wednesday": { "en": "Wednesday", + "ja": "水曜日", "zh": "星期三", "en-audio": "Wednesday" }, "rtc.thursday": { "en": "Thursday", + "ja": "木曜日", "zh": "星期四", "en-audio": "Thursday" }, "rtc.friday": { "en": "Friday", + "ja": "金曜日", "zh": "星期五", "en-audio": "Friday" }, "rtc.saturday": { "en": "Saturday", + "ja": "土曜日", "zh": "星期六", "en-audio": "Saturday" }, "rtc.sunday": { "en": "Sunday", + "ja": "日曜日", "zh": "星期日", "en-audio": "Sunday" }, "rtc.integer_err": { "en": "Error: entry was not numeric", + "ja": "エラー:エントリは数値ではありませんでした。", "zh": "错误:输入不是数字", "en-audio": "Error: entry was not numeric" }, "rtc.range_err": { "en": "Error: input out of range", + "ja": "エラー:入力が範囲外です。", "zh": "错误:输入超出范围", "en-audio": "Error: input out of range" } diff --git a/services/llio/src/llio_lib.rs b/services/llio/src/llio_lib.rs index 811d41dd2..1171e2682 100644 --- a/services/llio/src/llio_lib.rs +++ b/services/llio/src/llio_lib.rs @@ -16,7 +16,7 @@ pub struct Llio { } impl Llio { pub fn new(xns: &xous_names::XousNames) -> Self { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(SERVER_NAME_LLIO).expect("Can't connect to LLIO"); Llio { conn, @@ -405,8 +405,7 @@ impl Drop for Llio { if let Some(sid) = self.rtc_sid.take() { drop_conn(sid); } - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/llio/src/rtc_lib.rs b/services/llio/src/rtc_lib.rs index f08afd8bc..1f5f0c647 100644 --- a/services/llio/src/rtc_lib.rs +++ b/services/llio/src/rtc_lib.rs @@ -12,7 +12,7 @@ pub struct Rtc { static mut RTC_CB: Option = None; impl Rtc { pub fn new(xns: &xous_names::XousNames) -> Self { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(crate::api::SERVER_NAME_RTC).expect("Can't connect to RTC"); Rtc { conn, @@ -101,8 +101,7 @@ impl Drop for Rtc { // now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. // all implementations will need this - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index d2ddb8dfc..325fc7e92 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -16,7 +16,7 @@ pub struct Modals { } impl Modals { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_MODALS).expect("Can't connect to Modals server"); let trng = trng::Trng::new(&xns).unwrap(); let mut token = [0u32; 4]; @@ -250,8 +250,7 @@ impl Drop for Modals { // the connection to the server side must be reference counted, so that multiple instances of this object within // a single process do not end up de-allocating the CID on other threads before they go out of scope. // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), diff --git a/services/net/Cargo.toml b/services/net/Cargo.toml index 025ad483e..9610ba0b7 100644 --- a/services/net/Cargo.toml +++ b/services/net/Cargo.toml @@ -30,9 +30,10 @@ locales = {path = "../../locales"} pddb = {path = "../pddb"} [dependencies.smoltcp] -# ugh. have to reference `main` directly because they haven't pushed a new tag in months, and none -# of the worked examples match the actual documentation now. -# pin at a commit, at least, so we aren't building on shifting sand +# ugh. we startd pulling in smoltcp as they were just fixing a bunch of bugs and getting ready for a 0.8.0 release. +# this is the last commit that doesn't break things for Xous. They pulled in some random crate that isn't compatible +# with Xous in the commit after this -- we need to look into this and maybe send a PR so we can try to work with +# the latest smoltcp. But later...let's just get things even working first with what we have. git = "https://github.com/smoltcp-rs/smoltcp.git" rev = "35e833e33dfd3e4efc3eb7d5de06bec17c54b011" #path = "../../../smoltcp" diff --git a/services/net/locales/i18n.json b/services/net/locales/i18n.json index dafd0fba3..a1fce8eb1 100644 --- a/services/net/locales/i18n.json +++ b/services/net/locales/i18n.json @@ -1,11 +1,13 @@ { "net.ec_rev_old": { "en": "EC firmware is out of date. Wifi connection manager cannot start.", + "ja": "ECファームウェアが古くなっています。Wifiコネクションマネージャーが起動できません。", "zh": "EC 固件已过期,无法启动连接管理器.", "en-audio": "EC firmware is out of date. Wifi connection manager cannot start." }, "net.ec_current_rev": { "en": "Current EC rev: ", + "ja": "現在のEC rev: ", "zh": "当前的 EC 修订版: ", "en-audio": "Current EC rev: " } diff --git a/services/net/src/api.rs b/services/net/src/api.rs index 979e6cf9e..04d1d7a8f 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -41,6 +41,8 @@ pub(crate) enum Opcode { TcpTx, TcpClose, TcpManage, + TcpListen, + TcpManageListener, // The DNS server can hook the Net crate for notifications on config updates /// Adds an Ipv4 as a DNS server @@ -290,6 +292,7 @@ impl fmt::Debug for NetIpAddr { /// spaces: this is not the right object for passing messages from a remote server /// in a potentially hostile foreign process into your local memory space. /// See XousPrivateScalarHook for that function. +#[derive(Debug)] pub(crate) struct XousScalarEndpoint { cid: Option, op: Option, @@ -304,6 +307,9 @@ impl XousScalarEndpoint { args: [None; 4] } } + pub(crate) fn get(&self) -> (Option, Option, [Option; 4]) { + (self.cid, self.op, self.args) + } pub(crate) fn set(&mut self, cid: xous::CID, op: usize, args: [Option; 4]) { self.cid = Some(cid); self.op = Some(op); diff --git a/services/net/src/api/tcp.rs b/services/net/src/api/tcp.rs index 88559263d..b6e55f918 100644 --- a/services/net/src/api/tcp.rs +++ b/services/net/src/api/tcp.rs @@ -17,6 +17,20 @@ pub(crate) struct NetTcpManage { pub(crate) mgmt_code: Option, } +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) struct NetTcpListen { + pub(crate) cb_sid: [u32; 4], + pub(crate) local_port: u16, + pub(crate) result: Option, +} + +#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)] +pub(crate) struct NetTcpListenCallback { + pub(crate) ip_addr: NetIpAddr, + pub(crate) remote_port: u16, + pub(crate) local_port: u16, +} + #[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone, PartialEq, Eq)] pub(crate) enum TcpMgmtCode { SetRxShutdown, @@ -26,11 +40,13 @@ pub(crate) enum TcpMgmtCode { GetTtl(u32), ErrorCheck(NetMemResponse), Flush(bool), + CloseListener, } #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub(crate) enum NetTcpCallback { RxData, + ListenerActive, Drop, } diff --git a/services/net/src/main.rs b/services/net/src/main.rs index 34d77a20a..22e5c1d99 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -85,6 +85,7 @@ pub struct TcpConnection { remote_port: u16, local_port: u16, } +#[derive(Copy, Clone, Debug)] pub struct TcpState { handle: SocketHandle, cid: CID, @@ -178,6 +179,7 @@ fn xmain() -> ! { // tcp storage let mut tcp_handles = HashMap::::new(); + let mut tcp_listeners = HashMap::>::new(); // other link storage let neighbor_cache = NeighborCache::new(BTreeMap::new()); @@ -408,7 +410,7 @@ fn xmain() -> ! { let remote_port = tcpspec.remote_port; // initiates a new connection to a remote server consisting of an (Address:Port) tuple. - // multiple connections can exist to a server, and they are furhte differentiated by the return port + // multiple connections can exist to a server, and they are further differentiated by the return port let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]); let tcp_tx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]); let mut tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer); @@ -519,6 +521,10 @@ fn xmain() -> ! { tcpspec.mgmt_code = Some(TcpMgmtCode::Flush(false)); } } + TcpMgmtCode::CloseListener => { + // this is used for listener management, should never be sent to this routine + tcpspec.result = Some(NetMemResponse::LibraryError); + } } } else { tcpspec.result = Some(NetMemResponse::Invalid); @@ -572,6 +578,7 @@ fn xmain() -> ! { }; if let Some(tcp_state) = tcp_handles.remove(&connection) { sockets.get::(tcp_state.handle).close(); + sockets.remove(tcp_state.handle); tcpspec.result = Some(NetMemResponse::Ok); } else { tcpspec.result = Some(NetMemResponse::Invalid); @@ -581,6 +588,106 @@ fn xmain() -> ! { } buf.replace(tcpspec).unwrap(); } + Some(Opcode::TcpListen) => { + let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut tcpspec = buf.to_original::().unwrap(); + + let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]); + let tcp_tx_buffer = TcpSocketBuffer::new(vec![0; TCP_BUFFER_SIZE]); + let mut tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer); + match tcp_socket.listen(tcpspec.local_port) { + Ok(_) => { + if let Some(list) = tcp_listeners.get(&tcpspec.local_port) { + if list.len() > 0 { // empty check necessary because an empty vector is left if a socket went from listening->active, or was dropped + // guarantee that all TTLs are same even if we're inserting a new socket + let ttl = sockets.get::(list[0].handle).hop_limit(); + tcp_socket.set_hop_limit(ttl); + } + } + let handle = sockets.add(tcp_socket); + let sid = tcpspec.cb_sid; + let cid = xous::connect(SID::from_array(sid)).unwrap(); + let tcp_cb_state = TcpState { + handle, + cid, + shutdown_rx: false, + }; + if let Some(list) = tcp_listeners.get_mut(&tcpspec.local_port) { + list.push(tcp_cb_state); + } else { + tcp_listeners.insert(tcpspec.local_port, vec![tcp_cb_state]); + } + log::info!("creating listener on port {}", tcpspec.local_port); + tcpspec.result = Some(NetMemResponse::Ok); + } + Err(e) => { + match e { + smoltcp::Error::Illegal => { + tcpspec.result = Some(NetMemResponse::SocketInUse); + } + smoltcp::Error::Unaddressable => { + tcpspec.result = Some(NetMemResponse::Invalid); + } + _ => { + tcpspec.result = Some(NetMemResponse::LibraryError); + } + } + } + } + buf.replace(tcpspec).unwrap(); + }, + Some(Opcode::TcpManageListener) => { + let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; + let mut tcpspec = buf.to_original::().unwrap(); + match tcpspec.mgmt_code { + Some(TcpMgmtCode::CloseListener) => { + if let Some(listener) = tcp_listeners.get_mut(&tcpspec.local_port.unwrap()) { + if let Some(tcp_state) = listener.pop() { + sockets.get::(tcp_state.handle).close(); + log::info!("closing one listener on port {:?}", tcpspec.local_port); + sockets.remove(tcp_state.handle); + tcpspec.result = Some(NetMemResponse::Ok); + // this may leave an empty vector in the tcp_listeners structure, but I think that's OK + } + } else { + tcpspec.result = Some(NetMemResponse::Invalid); + } + } + Some(TcpMgmtCode::SetTtl(mut ttl)) => { + if let Some(listener_vec) = tcp_listeners.get_mut(&tcpspec.local_port.unwrap()) { + for listener in listener_vec.iter_mut() { + let mut socket = sockets.get::(listener.handle); + if ttl > 255 { ttl = 255; } + if ttl > 0 { + socket.set_hop_limit(Some(ttl as u8)); + } else { + socket.set_hop_limit(None); + } + } + tcpspec.result = Some(NetMemResponse::Ok); + } else { + tcpspec.result = Some(NetMemResponse::Invalid); + } + } + Some(TcpMgmtCode::GetTtl(_)) => { + if let Some(listener) = tcp_listeners.get(&tcpspec.local_port.unwrap()) { + if listener.len() > 0 { + // all listeners "should" have an identical setting, so, just return the setting of the 0th one + let socket = sockets.get::(listener[0].handle); + let value = socket.hop_limit().unwrap_or(64); // because that's what smoltcp does + tcpspec.mgmt_code = Some(TcpMgmtCode::GetTtl(value as u32)); + tcpspec.result = Some(NetMemResponse::Ok); + } else { + tcpspec.result = Some(NetMemResponse::Invalid); + } + } else { + tcpspec.result = Some(NetMemResponse::Invalid); + } + } + _ => tcpspec.result = Some(NetMemResponse::LibraryError), + } + buf.replace(tcpspec).unwrap(); + } Some(Opcode::UdpBind) => { let mut buf = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; let udpspec = buf.to_original::().unwrap(); @@ -660,6 +767,7 @@ fn xmain() -> ! { // if the clone map is nil, close the socket, we're done None => { sockets.get::(udpstate.handle).close(); + sockets.remove(udpstate.handle); buf.replace(NetMemResponse::Ok).unwrap(); } // if the clone map has entries, promote an arbitrary map entry to the primary handle @@ -668,6 +776,7 @@ fn xmain() -> ! { // removing SIDs doesn't remove the map, so it's possible to have an empty mapping. Get rid of it, and we're done. udp_clones.remove(&udpspec.port); sockets.get::(udpstate.handle).close(); + sockets.remove(udpstate.handle); buf.replace(NetMemResponse::Ok).unwrap(); } else { // take an arbitrary key, re-insert it into the handles map. @@ -946,6 +1055,53 @@ fn xmain() -> ! { } } + // this block handles TCP listeners + // There is no lock on sending Rx messages to the listener as it is being transformed + // because all messages come from *this thread* and by definition it is not re-entrant. + // If you end up splitting the Tcp Rx task and the Tcp Listener tasks into separate threads, + // Then you must worry about the possibility of a race condition between the transition of a + // TcpListener to a regular TcpStream client (that is, an Rx packet forwarded before the + // TcpStream is fully built). + if tcp_listeners.len() > 0 { // skip the whole chunk if we don't have any tcp listeners + for (&local_port, tcp_state_vec) in tcp_listeners.iter_mut() { + let mut remove_indices = Vec::::new(); + for (index, tcp_state) in tcp_state_vec.iter().enumerate() { + let socket = sockets.get::(tcp_state.handle); + if socket.is_active() { + log::info!("Promoting a listener on port {:?} to a stream", socket.local_endpoint()); + // 1. promote this socket to a TCP rx socket (this creates a double-entry that is cleaned up in step 3) + let connection = TcpConnection { + remote: socket.remote_endpoint().addr, + remote_port: socket.remote_endpoint().port, + local_port, + }; + tcp_handles.insert(connection, *tcp_state); + + // 2. notify the listener + let note = NetTcpListenCallback { + ip_addr: NetIpAddr::from(socket.remote_endpoint().addr), + remote_port: socket.remote_endpoint().port, + local_port, + }; + log::info!("Listener active, notification sent to {}: {:?}", tcp_state.cid, note); + let buf = Buffer::into_buf(note).expect("can't transform memory message"); + buf.send(tcp_state.cid, NetTcpCallback::ListenerActive.to_u32().unwrap()).expect("can't inform callback of active status"); + remove_indices.push(index); + } + } + // 3. now cleanup and remove the ports from the listeners status + remove_indices.sort(); // this should be in ascending order, but let's do this just to be sure. + remove_indices.reverse(); + for index in remove_indices { + tcp_state_vec.remove(index); + } + // 4. At this point, the Listener is no more. However, the caller side will "renew" the + // listener if the TcpListener is being used in an `incoming` loop. + + // 5. Side note: an empty vector could be left in the tcp_listeners array. 🔥This is fine🔥. + } + } + // this block handles UDP { for (port, udpstate) in udp_handles.iter() { diff --git a/services/net/src/protocols.rs b/services/net/src/protocols.rs index 2ad760b75..a641c4ac5 100644 --- a/services/net/src/protocols.rs +++ b/services/net/src/protocols.rs @@ -5,4 +5,6 @@ pub use dns::*; pub mod ping; pub use ping::*; pub mod tcp_stream; -pub use tcp_stream::*; \ No newline at end of file +pub use tcp_stream::*; +pub mod tcp_listener; +pub use tcp_listener::*; diff --git a/services/net/src/protocols/tcp_listener.rs b/services/net/src/protocols/tcp_listener.rs index bc38c5de5..1da707d33 100644 --- a/services/net/src/protocols/tcp_listener.rs +++ b/services/net/src/protocols/tcp_listener.rs @@ -1,52 +1,281 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs}; +use std::unimplemented; +use std::io; +use std::io::{Error, ErrorKind, Result}; +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::fmt; +use std::collections::VecDeque; -// this is if we need to be a server. implement this second. -pub struct TcpListener(!); +use xous::{Message, SID, CID}; +use xous_ipc::Buffer; +use crate::TcpStream; +use crate::NetConn; +use crate::api::*; +use num_traits::*; + +const LISTENER_POLL_INTERVAL_MS: usize = 250; + +pub struct TcpListener { + net: NetConn, + cb_sid: SID, + ticktimer: ticktimer_server::Ticktimer, + xns: xous_names::XousNames, + refcount: Arc, + port: u16, + nonblocking: bool, + original_notify: XousScalarEndpoint, + + // reserved for when the responder thread is "promoted" to active status + rx_buf: Arc::>>, + /// xous-specific feature that allows for more efficent Rx than blocking. Caller must set_scalar_notification() to use it. + rx_notify: Arc>, + listener_info: Arc>>, +} impl TcpListener { - pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { - unsupported() + pub fn bind(maybe_socket: io::Result<&SocketAddr>) -> io::Result { + TcpListener::bind_inner(maybe_socket) } - pub fn socket_addr(&self) -> io::Result { - self.0 + pub fn bind_xous(addr: A) -> Result { + match addr.to_socket_addrs() { + Ok(socks) => { + match socks.into_iter().next() { + Some(socket_addr) => { + TcpListener::bind_inner( + Ok(&socket_addr), + ) + } + _ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } + } + _ => Err(Error::new(ErrorKind::InvalidInput, "IP address invalid")) + } } - pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { - self.0 + pub fn bind_inner(maybe_socket: io::Result<&SocketAddr>) -> io::Result { + let socket = maybe_socket?; + let xns = xous_names::XousNames::new().unwrap(); + let net = NetConn::new(&xns).unwrap(); + let cb_sid = xous::create_server().unwrap(); + let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); + + let rx_buf = Arc::new(Mutex::new(VecDeque::::new())); + rx_buf.lock().unwrap().reserve(TCP_BUFFER_SIZE); + let notify = Arc::new(Mutex::new(XousScalarEndpoint::new())); + let listener_info = Arc::new(Mutex::new(None::)); + + let _handle = crate::tcp_rx_thread( + cb_sid.clone(), + Arc::clone(&rx_buf), + Arc::clone(¬ify), + // this is not used by TcpStream + Arc::clone(&listener_info) + ); + let request = NetTcpListen { + cb_sid: cb_sid.to_array(), + local_port: socket.port(), + result: None, + }; + log::info!("Attempting to bind a listener to port {}", socket.port()); + let mut buf = Buffer::into_buf(request) + .or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?; + buf.lend_mut(net.conn(), Opcode::TcpListen.to_u32().unwrap()) + .or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?; + let ret = buf.to_original::().unwrap(); + log::info!("Got result: {:?}", ret.result); + match ret.result { + Some(NetMemResponse::Ok) => { + Ok(TcpListener { + net, + cb_sid, + ticktimer, + xns, + refcount: Arc::new(AtomicU32::new(1)), // one instance, that's me! + port: socket.port(), + rx_buf, + rx_notify: notify, + listener_info, + nonblocking: false, + original_notify: XousScalarEndpoint::new(), + }) + } + _ => { + Err(Error::new(ErrorKind::Other, "can't create Listener with Net server")) + } + } + } + pub fn set_scalar_notification(&mut self, cid: CID, op: usize, args: [Option; 4]) { + self.original_notify.set(cid, op, args); + self.rx_notify.lock().unwrap().set(cid, op, args); + } + pub fn clear_scalar_notification(&mut self) { + self.original_notify.clear(); + self.rx_notify.lock().unwrap().clear(); } - pub fn duplicate(&self) -> io::Result { - self.0 + pub fn accept(&mut self) -> io::Result<(TcpStream, SocketAddr)> { + let mut prints = 0; + loop { + let accepted = if let Some(info) = self.listener_info.lock().unwrap().take() { + // 1. Create a new TcpStream object using our existing handles + let remote = SocketAddr::new(IpAddr::from(info.ip_addr), info.remote_port); + log::info!("building stream to {:?}", remote); + let stream = TcpStream::build_from_listener( + NetConn::new(&self.xns).unwrap(), + self.cb_sid, + remote, + info.local_port, + std::mem::replace(&mut self.rx_buf, Arc::new(Mutex::new(VecDeque::::new()))), + // we keep our notifier for ourself, create a new one for the passed-on thread + Arc::new(Mutex::new(XousScalarEndpoint::new())), + ); + Some((stream, remote)) + } else { + if self.nonblocking { + return Err(Error::new(ErrorKind::WouldBlock, "accept would block")); + } + None + }; + if let Some((stream, remote)) = accepted { + log::info!("replenishing listener, notifier: {:?}", self.rx_notify); + // 2. Replenish our Listener objects and pass a TcpListen message on to the Net manager to repeat the cycle + self.listener_info = Arc::new(Mutex::new(None::)); + self.cb_sid = xous::create_server().unwrap(); + // create a new notify arc/mutex, then copy the master notification settings there + self.rx_notify = Arc::new(Mutex::new(XousScalarEndpoint::new())); + if self.original_notify.is_set() { + let (c, o, a) = self.original_notify.get(); + self.rx_notify.lock().unwrap().set(c.unwrap(), o.unwrap(), a); + } + let _handle = crate::tcp_rx_thread( + self.cb_sid.clone(), + Arc::clone(&self.rx_buf), + // we're re-using the notifier object...is this going to be a problem? + Arc::clone(&self.rx_notify), + // this is not used by TcpStream + Arc::clone(&self.listener_info) + ); + let request = NetTcpListen { + cb_sid: self.cb_sid.to_array(), + local_port: stream.socket_addr().unwrap().port(), + result: None, + }; + let mut buf = Buffer::into_buf(request) + .or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?; + buf.lend_mut(self.net.conn(), Opcode::TcpListen.to_u32().unwrap()) + .or(Err(Error::new(ErrorKind::Other, "can't register with Net server")))?; + let ret = buf.to_original::().unwrap(); + return + match ret.result { + Some(NetMemResponse::Ok) => Ok((stream, remote)), + _ => Err(Error::new(ErrorKind::Other, "can't renew Listener with Net server")) + } + } + if prints < 10 { + log::info!("accept polling..."); + prints += 1; + } + self.ticktimer.sleep_ms(LISTENER_POLL_INTERVAL_MS).unwrap(); + } } - pub fn set_ttl(&self, _: u32) -> io::Result<()> { - self.0 + pub fn local_addr(&self) -> io::Result { + Ok(SocketAddr::new( + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), + self.port + )) + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.tcp_manage(TcpMgmtCode::SetTtl(ttl)).map(|_| ()) } pub fn ttl(&self) -> io::Result { - self.0 - } - - pub fn set_only_v6(&self, _: bool) -> io::Result<()> { - self.0 - } - - pub fn only_v6(&self) -> io::Result { - self.0 + match self.tcp_manage(TcpMgmtCode::GetTtl(0)) { + Ok(TcpMgmtCode::GetTtl(value)) => Ok(value), + _ => Err(Error::new(ErrorKind::Other, "Internal error")), + } } + /// I'm not really sure what this does on Xous, as we don't have a SO_ERROR value in our OS. + /// Just returning Ok(None) for now. pub fn take_error(&self) -> io::Result> { - self.0 + Ok(None) } - pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { - self.0 + pub fn set_nonblocking(&mut self, setting: bool) -> io::Result<()> { + self.nonblocking = setting; + Ok(()) + } + + pub fn duplicate(&self) -> io::Result { + Err(Error::new(ErrorKind::Other, "Xous does not support cloned listeners")) + } + + fn tcp_manage(&self, code: TcpMgmtCode) -> io::Result { + // only local_port is needed + let request = NetTcpManage { + cb_sid: self.cb_sid.to_array(), + ip_addr: NetIpAddr::Ipv4([127, 0, 0, 1]), + remote_port: 0, + local_port: Some(self.port), + timeout_ms: None, + keepalive_ms: None, + result: None, + mgmt_code: Some(code), + }; + let mut buf = Buffer::into_buf(request) + .or(Err(Error::new(ErrorKind::Other, "can't manage TCP")))?; + buf.lend_mut(self.net.conn(), Opcode::TcpManageListener.to_u32().unwrap()) + .or(Err(Error::new(ErrorKind::Other, "can't manage TCP")))?; + let ret = buf.to_original::().unwrap(); + if let Some(code) = ret.mgmt_code { + Ok(code) + } else { + Err(Error::new(ErrorKind::Other, "Internal error")) + } } } impl fmt::Debug for TcpListener { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0 + unimplemented!() } } +impl Drop for TcpListener { + fn drop(&mut self) { + if self.refcount.fetch_sub(1, Ordering::SeqCst) == 1 { + // the only thing we really need from the management structure for this call is the local port... + let request = NetTcpManage { + ip_addr: NetIpAddr::from(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))), + remote_port: 0, // bogus port + local_port: Some(self.port), + cb_sid: self.cb_sid.to_array(), + timeout_ms: None, + keepalive_ms: None, + result: None, + mgmt_code: Some(TcpMgmtCode::CloseListener), + }; + let mut buf = Buffer::into_buf(request).expect("can't unregister with Net server"); + buf.lend_mut(self.net.conn(), Opcode::TcpManageListener.to_u32().unwrap()).expect("can't unregister with Net server"); + match buf.to_original().unwrap() { + NetMemResponse::Ok => { + let drop_cid = xous::connect(self.cb_sid).unwrap(); + xous::send_message( + drop_cid, + Message::new_blocking_scalar(NetTcpCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("couldn't send Drop to our repsonding server"); + unsafe{xous::disconnect(drop_cid).ok()}; // should be safe because we're the only connection and the previous was a blocking scalar + }, + _ => { + panic!("Couldn't unregister with net server"); + } + } + // now we can detroy the server id of the responder thread + xous::destroy_server(self.cb_sid).ok(); + } + } +} \ No newline at end of file diff --git a/services/net/src/protocols/tcp_stream.rs b/services/net/src/protocols/tcp_stream.rs index fa6b5f7b4..b599ee1b4 100644 --- a/services/net/src/protocols/tcp_stream.rs +++ b/services/net/src/protocols/tcp_stream.rs @@ -13,7 +13,6 @@ use xous::{CID, Message, SID, msg_blocking_scalar_unpack}; use xous_ipc::Buffer; use crate::NetConn; use crate::api::*; -//use crate::api::udp::*; use num_traits::*; use std::net::Shutdown; @@ -45,6 +44,33 @@ pub struct TcpStream { } impl TcpStream { + /// This is routine that allows a TcpListener to create a TcpStream object. The following must be observed: + /// 1. The `cb_sid`, `rx_buf` and `rx_notify` are the memory locations mapped into the already-allocated Rx thread + /// 2. These fields are not to be re-used in the Listener object that succeeds the current one + pub(crate) fn build_from_listener( + net: NetConn, + cb_sid: SID, + remote: SocketAddr, + local_port: u16, + rx_buf: Arc::>>, + rx_notify: Arc>, + ) -> TcpStream { + TcpStream { + net, + cb_sid, + socket_addr: remote, + local_port, + rx_buf, + rx_notify, + read_timeout: None, + write_timeout: None, + ticktimer: ticktimer_server::Ticktimer::new().unwrap(), + nonblocking: false, + rx_shutdown: false, + tx_shutdown: false, + rx_refcount: Arc::new(AtomicU32::new(1)), + } + } pub fn connect(maybe_socket: io::Result<&SocketAddr>) -> io::Result { TcpStream::connect_inner(maybe_socket, None, None) } @@ -85,38 +111,13 @@ impl TcpStream { rx_buf.lock().unwrap().reserve(TCP_BUFFER_SIZE); let notify = Arc::new(Mutex::new(XousScalarEndpoint::new())); - let _handle = thread::spawn({ - let cb_sid_clone = cb_sid.clone(); - let rx_buf = Arc::clone(&rx_buf); - let notify = Arc::clone(¬ify); - move || { - loop { - let msg = xous::receive_message(cb_sid_clone).unwrap(); - match FromPrimitive::from_usize(msg.body.id()) { - Some(NetTcpCallback::RxData) => { - let buffer = unsafe {Buffer::from_memory_message(msg.body.memory_message().unwrap())}; - let incoming = buffer.as_flat::().unwrap(); - log::trace!("rx data({})", incoming.len); - { // grab the lock once for better efficiency - let mut rx_locked = rx_buf.lock().unwrap(); - for &d in incoming.data[..incoming.len as usize].iter() { - rx_locked.push_back(d); - } - } - notify.lock().unwrap().notify(); // this will only notify if a destination has been set - } - Some(NetTcpCallback::Drop) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { - log::debug!("Drop received, exiting Tcp handler"); - xous::return_scalar(msg.sender, 1).unwrap(); - break; - }), - None => { - log::error!("got unknown message type on Tcp callback: {:?}", msg); - } - } - } - } - }); + let _handle = tcp_rx_thread( + cb_sid.clone(), + Arc::clone(&rx_buf), + Arc::clone(¬ify), + // this is not used by TcpStream + Arc::new(Mutex::new(None::)), + ); let request = NetTcpManage { cb_sid: cb_sid.to_array(), @@ -321,8 +322,17 @@ impl TcpStream { Ok(cloned_stream) } - pub fn peek(&self, _: &mut [u8]) -> io::Result { - unimplemented!() + pub fn peek(&self, buf: &mut [u8]) -> io::Result { + if self.rx_buf.lock().unwrap().len() == 0 { + return Ok(0) + } else { + let rx_buf = self.rx_buf.lock().unwrap(); + let readlen = rx_buf.len().min(buf.len()); + for (&src, dst) in rx_buf.range(..readlen).zip(buf.iter_mut()) { + *dst = src; + } + return Ok(readlen) + } } } @@ -504,4 +514,50 @@ impl Drop for TcpStream { xous::destroy_server(self.cb_sid).ok(); } } +} + +pub(crate) fn tcp_rx_thread( + cb_sid_clone: SID, + rx_buf: Arc::>>, + notify: Arc::>, + listener: Arc::>>, +) -> std::thread::JoinHandle<()> { + thread::spawn({ + move || { + loop { + let msg = xous::receive_message(cb_sid_clone).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(NetTcpCallback::RxData) => { + let buffer = unsafe {Buffer::from_memory_message(msg.body.memory_message().unwrap())}; + let incoming = buffer.as_flat::().unwrap(); + log::trace!("rx data({})", incoming.len); + { // grab the lock once for better efficiency + let mut rx_locked = rx_buf.lock().unwrap(); + for &d in incoming.data[..incoming.len as usize].iter() { + rx_locked.push_back(d); + } + } + notify.lock().unwrap().notify(); // this will only notify if a destination has been set + } + Some(NetTcpCallback::ListenerActive) => { + let buffer = unsafe {Buffer::from_memory_message(msg.body.memory_message().unwrap())}; + let incoming = buffer.to_original::().unwrap(); + // notify the caller that it should pick up its state + log::info!("Setting the notifier structure from {:?} to Some({:?})", listener, incoming); + *listener.lock().unwrap() = Some(incoming); + log::info!("After: {:?}", listener); + notify.lock().unwrap().notify(); // this will only notify if a destination has been set + } + Some(NetTcpCallback::Drop) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + log::debug!("Drop received, exiting Tcp handler"); + xous::return_scalar(msg.sender, 1).unwrap(); + break; + }), + None => { + log::error!("got unknown message type on Tcp callback: {:?}", msg); + } + } + } + } + }) } \ No newline at end of file diff --git a/services/pddb/locales/i18n.json b/services/pddb/locales/i18n.json index 702cce056..09659622a 100644 --- a/services/pddb/locales/i18n.json +++ b/services/pddb/locales/i18n.json @@ -1,106 +1,127 @@ { "pddb.okay": { "en": "Okay", + "ja": "OK", "zh": "确定", "en-audio": "Okay" }, "pddb.cancel": { "en": "Cancel", + "ja": "キャンセル", "zh": "取消", "en-audio": "Cancel" }, "pddb.yes": { "en": "Yes", + "ja": "はい", "zh": "是的", "en-audio": "Yes" }, "pddb.no": { "en": "No", + "ja": "いいえ", "zh": "不", "en-audio": "No" }, "pddb.badpass": { "en": "Incorrect password.\n\nTry again?\n", + "ja": "パスワードを認証失敗でした。\n\nもう一度実行しませんか。\n", "zh": "密码错误。 再试一次?", "en-audio": "Incorrect password. Try again?" }, "pddb.checkpass": { "en": "Press any key, then re-enter your password for setup confirmation.", + "ja": "任意キーを押して、パスワードを再入力してセットアップを確認してください。", "zh": "第一次使用,再次输入密码", "en-audio": "First-time setup: Enter password again." }, "pddb.checkpass_fail": { "en": "Password mismatch!\n\nPlease try again.", + "ja": "パスワード一致していません!\n\nもう一度実行しください。", "zh": "密码不匹配,请重试.", "en-audio": "Password mismatch! Please try again." }, "pddb.badpass_infallible": { "en": "Incorrect password.\n\nPlease try again.", + "ja": "パスワードを認証失敗でした。\n\nもう一度実行しください。", "zh": "密码错误。", "en-audio": "Incorrect password. Please try again." }, "pddb.requestformat": { "en": "The PDDB storage needs formatting. This takes about 15 minutes and can't be interrupted.\n\nProceed?", + "ja": "PDDBストレージのフォーマットが必要です。これは約15分かかり、中断することはできません。\n\n続行しますか?", "zh": "存储需要格式化。这需要15分钟。继续?", "en-audio": "The PDDB storage needs formatting. It will take about 15 minutes and can't be interrupted. Proceed?" }, "pddb.devbypass": { "en": "Are you testing the PDDB?", + "ja": "PDDBをテストしているのか?", "zh": "你在测试存储吗?", "en-audio": "Are you testing the PDDB?" }, "pddb.erase": { "en": "Bulk erase\n(1/6)", + "ja": "一括削除\n(1/6)", "zh": "擦除存储(1/6)", "en-audio": "Bulk erase step 1 of 6" }, "pddb.initpt": { "en": "Pagetable\n(2/6)", + "ja": "ページテーブル\n(2/6)", "zh": "分页表(2/6)", "en-audio": "Pagetable step 2 of 6" }, "pddb.key": { "en": "Keys\n(3/6)", + "ja": "キー\n(3/6)", "zh": "密钥(3/6)", "en-audio": "Keys step 3 of 6" }, "pddb.fastspace": { "en": "Fastspace\n(4/6)", + "ja": "ファーストスペース\n(4/6)", "zh": "快空间(4/6)", "en-audio": "Fastspace step 4 of 6" }, "pddb.randomize": { "en": "Cryptographic wipe\n(5/6)", + "ja": "クリプトワイプ\n(5/6)", "zh": "随机存储(5/6)", "en-audio": "Randomize disk step 5 of 6" }, "pddb.structure": { "en": "Commit root\n(6/6)", + "ja": "コミットルート\n(6/6)", "zh": "提交根(6/6)", "en-audio": "Commit root step 6 of 6" }, "pddb.internalerror": { "en": "Internal Error", + "ja": "内部エラー", "zh": "内部错误", "en-audio": "Internal Error" }, "pddb.basisname": { "en": "Basis Name:", + "ja": "Basis名", "zh": "基础名称", "en-audio": "Enter name of Basis" }, "pddb.password": { "en": "Basis Password:", + "ja": "Basis パスワード", "zh": "基础密码", "en-audio": "Enter password for Basis" }, "pddb.menu.listbasis": { "en": "List unlocked bases", + "ja": "ロック解除されたベースをー覧表します", "zh": "基础列表", "en-audio": "List unlocked bases" }, "pddb.menu.listbasis_response": { "en": "Unlocked bases:\n", + "ja": "ロック解除されたベース:\n", "zh": "透露列表:\n", "en-audio": "Unlocked bases:" } diff --git a/services/pddb/src/frontend/pddbkey.rs b/services/pddb/src/frontend/pddbkey.rs index 56a6f1c62..bc37c801f 100644 --- a/services/pddb/src/frontend/pddbkey.rs +++ b/services/pddb/src/frontend/pddbkey.rs @@ -152,8 +152,7 @@ impl<'a> Drop for PddbKey<'a> { send_message(self.conn, Message::new_blocking_scalar(Opcode::KeyDrop.to_usize().unwrap(), self.token[0] as usize, self.token[1] as usize, self.token[2] as usize, 0)).expect("couldn't send KeyDrop message"); - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/pddb/src/lib.rs b/services/pddb/src/lib.rs index 4e7e42cbb..78b4e0646 100644 --- a/services/pddb/src/lib.rs +++ b/services/pddb/src/lib.rs @@ -50,7 +50,7 @@ pub struct Pddb { } impl Pddb { pub fn new() -> Self { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let xns = xous_names::XousNames::new().unwrap(); let conn = xns.request_connection_blocking(api::SERVER_NAME_PDDB).expect("can't connect to Pddb server"); let sid = xous::create_server().unwrap(); @@ -294,7 +294,7 @@ impl Pddb { if let Some(cb) = key_changed_cb { self.keys.lock().unwrap().insert(token, Box::new(cb)); } - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let pk = PddbKey { // i think these fields are redundant, let's save the storage and remove them for now... //dict: String::from(dict_name), @@ -526,8 +526,7 @@ impl Drop for Pddb { handle.join().expect("couldn't terminate callback helper thread"); } - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/root-keys/locales/i18n.json b/services/root-keys/locales/i18n.json index 0b9476c59..4cbb563b4 100644 --- a/services/root-keys/locales/i18n.json +++ b/services/root-keys/locales/i18n.json @@ -1,241 +1,289 @@ { "rootkeys.bootpass": { "en": "Create a PIN code for device unlock.", + "ja": "デバイスのロックを解除するためのPINコードを作成します。", "zh": "输入密码 解锁 安全含义:低", "en-audio": "Enter unlock password" }, "rootkeys.updatepass": { "en": "⚠ Critical Password ⚠\nCreate a strong passphrase for authorizing system updates.", + "ja": "重要なパスワード\nシステムアップデートを認証するための強力なパスフレーズを作成します。", "zh": "输入密码 软件更新 安全含义:至关重要 ", "en-audio": "Enter update password. This password is critically important." }, "rootkeys.already_init": { "en": "Root keys already initialized.", + "ja": "ルートキーはすでに初期化されています。", "zh": "根密码已经设置", "en-audio": "Root keys already initialized." }, "rootkeys.confirm": { "en": "This will initialize the root keys on your Precursor device.\n\nYou will be prompted for two passwords:\n\t1. Device unlock PIN code\n\t2. System update passphrase.\n\nAre you ready?", + "ja": "これにより、Precursorデバイスのルートキーが初期化されます。\n\n2つのパスワードの入力を求められます。\n\t1.デバイスのロック解除PINコード\n\t2.システムアップデートパスフレーズ。\n\n準備はいいですか?", "zh": "仅当您准备好信 任此设备时才 应继续", "en-audio": "You should only proceed with this operation if you are ready to trust this device." }, "rootkeys.confirm.yes": { "en": "I'm ready!", + "ja": "準備OK!", "zh": "确定", "en-audio": "I'm ready!" }, "rootkeys.confirm.no": { "en": "Not yet, maybe later.", + "ja": "まだです、多分後で。", "zh": "我先检查一下,稍后再试", "en-audio": "I'll try again after inspecting my device." }, "rootkeys.setup_wait": { "en": "Initializing keys. This takes a few minutes. Do not reset or sleep!", + "ja": "キーを初期化中です。これには数分かかります。リセットやスリープはしないでください。", "zh": "现在正在初始化 可能还要等一下 不要重置或睡眠! ", "en-audio": "Initializing keys. This may take a while, don't reset or sleep the device." }, "rootkeys.init.signing_loader": { "en": "Signing loader. This takes a few minutes. Do not reset or sleep!", + "ja": "ローダーは署名中です。これには数分かかります。リセットやスリープはしないでください。", "zh": "签名引导程序 可能还要等一下 不要重置或睡眠! ", "en-audio": "Signing loader. This may take a while, don't reset or sleep the device." }, "rootkeys.init.signing_kernel": { "en": "Signing kernel. This takes a few minutes. Do not reset or sleep!", + "ja": "カーネルへを署名中です。これには数分かかります。リセットやスリープはしないでください。", "zh": "签名内核 可能还要等一下 不要重置或睡眠! ", "en-audio": "Signing kernel. This may take a while, don't reset or sleep the device." }, "rootkeys.init.backup_gateware": { "en": "Backing up gateware. This takes a few minutes. Do not reset or sleep!", + "ja": "ゲートウェアをバックアップ中です。これには数分かかります。リセットやスリープはしないでください。", "zh": "备份比特流 可能还要等一下 不要重置或睡眠! ", "en-audio": "Backing up gateware. This may take a while, don't reset or sleep the device." }, "rootkeys.init.patching_keys": { "en": "Injecting new keys. This takes a few minutes. Do not reset or sleep!", + "ja": "新しいキーを挿入中です。これには数分かかります。リセットやスリープはしないでください。", "zh": "更换新钥匙 可能还要等一下 不要重置或睡眠! ", "en-audio": "Injecting new keys. This may take a while, don't reset or sleep the device." }, "rootkeys.init.verifying_gateware": { "en": "Verifying new gateware. This takes a few minutes. Do not reset or sleep!", + "ja": "新しいゲートウェアの検証中です。これには数分かかります。リセットやスリープはしないでください。", "zh": "验证比特流 可能还要等一下 不要重置或睡眠! ", "en-audio": "Verifying gateware. This may take a while, don't reset or sleep the device." }, "rootkeys.init.commit_signatures": { "en": "Committing signatures. This takes a few minutes. Do not reset or sleep!", + "ja": "署名のコミット中です。これには数分かかります。リセットやスリープはしないでください。", "zh": "保存签名 可能还要等一下 不要重置或睡眠! ", "en-audio": "Committing signatures. This may take a while, don't reset or sleep the device." }, "rootkeys.init.unplug_power": { "en": "Please unplug the charging cable so I can reboot! ", + "ja": "再起動できるように、充電ケーブルを抜いてください。", "zh": "拔下充电线以允许重启!", "en-audio": "Unplug the charging cable so I can reboot!" }, "rootkeys.init.finished": { "en": "Rebooting now... ", + "ja": "再起動中...", "zh": "准备重启... ", "en-audio": "Rebooting now." }, "rootkeys.init.fail_verify": { "en": "Verification failed, aborting!", + "ja": "検証に失敗し、中止します!", "zh": "*missing*正在初始化失败,中止!", "en-audio": "Verification failed, aborting" }, "rootkeys.init.fail_key": { "en": "FPGA key is wrong: Perhaps the update password was entered incorrectly?", - "zh": "*missing*正在初始化失败,中止!", + "ja": "FPGAキーが間違っています: 更新パスワードが間違って入力された可能性がありますか?", + "zh": "*missing*正在初始化失败,中止します!", "en-audio": "FPGA key is wrong, perhaps the update password was entered incorrectly?" }, "rootkeys.init.fail_burn": { "en": "FLASH write problem, aborting!", + "ja": "フラッシュ書き込みの問題、中止します!", "zh": "*missing*正在初始化失败,中止!", "en-audio": "FLASH write problem, aborting" }, "rootkeys.init.fail_alignment": { "en": "Internal alignment error, aborting!", + "ja": "内部アライメントエラー、中止します!", "zh": "*missing*正在初始化失败,中止!", "en-audio": "Internal alignment error, aborting" }, "rootkeys.init.confirmation": { "en": "This cannot be undone. Continue?", + "ja": "これは元に戻せません。続けますか?", "zh": "这无法撤消,要继续吗?", "en-audio": "This cannot be undone. Continue?" }, "rootkeys.gwup.no_update_found": { "en": "No valid update found, aborting!", + "ja": "有効な更新が見つかりませんでした。中止します!", "zh": "未找到有效更新,正在中止!", "en-audio": "No valid update found, aborting" }, "rootkeys.gwup.inspecting": { "en": "Inspecting update, please wait...", + "ja": "アップデートを確認しています、お待ちください...", "zh": "正在检查比特流,请稍候...", "en-audio": "Inspecting update, please wait." }, "rootkeys.gwup.viewinfo_ss": { "en": "Self-signed image found. Review details?", + "ja": "自己署名画像が見つかりました。 詳細を確認しますか?", "zh": "**missing**查看更新的详细信息?", "en-audio": "Self-signed image found. Review details?" }, "rootkeys.gwup.viewinfo_tp": { "en": "Third party image found. Review details?", + "ja": "サードパーティの画像が見つかりました。 詳細を確認しますか?", "zh": "**missing**查看更新的详细信息?", "en-audio": "Self-signed image found. Review details?" }, "rootkeys.gwup.viewinfo_dk": { "en": "Devkey image found. Review details?", + "ja": "Devkeyの画像が見つかりました。 詳細を確認しますか?", "zh": "**missing**查看更新的详细信息?", "en-audio": "Self-signed image found. Review details?" }, "rootkeys.gwup.details": { "en": "All details", + "ja": "すべての詳細", "zh": "所有细节", "en-audio": "All details" }, "rootkeys.gwup.short": { "en": "Short summary", + "ja": "簡単な要約", "zh": "简短的摘要", "en-audio": "Short summary" }, "rootkeys.gwup.none": { "en": "Skip", + "ja": "スキップ", "zh": "跳过这步", "en-audio": "Skip" }, "rootkeys.gwup.proceed_confirm": { "en": "Proceed with update?", + "ja": "更新を続行しますか?", "zh": "继续更新?", "en-audio": "Proceed with update?" }, "rootkeys.gwup.yes": { "en": "Yes", + "ja": "はい", "zh": "确定", "en-audio": "Yes" }, "rootkeys.gwup.no": { "en": "No", + "ja": "いいえ", "zh": "取消", "en-audio": "No" }, "rootkeys.gwup_starting": { "en": "Updating gateware. This takes a few minutes.\nDo not reset or sleep!", + "ja": "ゲートウェアをアップデート中です。これには数分かかります。\nリセットやスリープはしないでください。", "zh": "现在正在初始化 可能还要等一下 不要重置或睡眠! ", "en-audio": "Updating gateware. This may take a while, don't reset or sleep the device." }, "rootkeys.get_update_password": { "en": "⚠ Critical password request ⚠\nEnter the 'SYSTEM UPDATE' passphrase. This authorizes a system update.", + "ja": "重要なパスワード要求\nSYSTEM UPDATEのパスフレーズを入力してください。これでシステムアップデートが許可されます。", "zh": "输入密码 软件更新 安全含义:至关重要 ", "en-audio": "Enter update password, in order to authorize a gateware update." }, "rootkeys.gwup.finished": { "en": "Gateware update finished.\nReboot at your earliest convenience.", + "ja": "ゲートウェアアップデートが終了しました。ご都合の良い時に再起動してください。", "zh": "更新完成重启应用", "en-audio": "Gateware update finished. Reboot at your earliest convenience." }, "rootkeys.bbram.confirm": { "en": "Connect provisioning helper, then press enter. Refer to https://github.com/betrusted-io/betrusted-wiki/wiki for details.", + "ja": "プロビジョニングヘルパーを接続し、Enterキーを押してください。詳しくは、https://github.com/betrusted-io/betrusted-wiki/wiki を参照してください。", "zh": "立即连接配置助手。请参阅 https://github.com/betrusted-io/betrusted-wiki/wiki 了解详情。", "en-audio": "Connect provisioning helper then press enter. Refer to https://github.com/betrusted-io/betrusted-wiki/wiki for details." }, "rootkeys.bbram.finished": { "en": "BBRAM helper should have rebooted the device. There was a problem with the procedure!", + "ja": "BBRAMヘルパーはデバイスをリブートしたはずです。手順に問題がありました!", "zh": "**missing**", "en-audio": "BBRAM helper should have rebooted the device, you should not get this message!" }, "rootkeys.bbram.failed_restore": { "en": "Something went wrong. Restoring from backup... ", + "ja": "何かがうまくいきませんでした。 バックアップからの復元中です...", "zh": "出了点问题,从备份中恢复...", "en-audio": "Something went wrong, restoring from backup." }, "rootkeys.console_input": { "en": "Communicating with helper... Press enter to abort.", + "ja": "ヘルパーと通信しています... Enterキーを押して中止します。", "zh": "与助手通信,按 Enter 中止", "en-audio": "Communicating with helper. Press enter to abort." }, "rootkeys.bbram.no_helper": { "en": "No BBRAM helper found. Refer to https://github.com/betrusted-io/betrusted-wiki/wiki for help.", + "ja": "BBRAMヘルパーが見つかりませんでした。https://github.com/betrusted-io/betrusted-wiki/wiki を参照してください。", "zh": "没有找到 BBRAM helper。参考https://github.com/betrusted-io/betrusted-wiki/wiki。", "en-audio": "No BBRAM helper found. Refer to https://github.com/betrusted-io/betrusted-wiki/wiki for help." }, "rootkeys.get_signing_password": { "en": "⚠ Critical password request ⚠\nEnter the 'SYSTEM UPDATE' passphrase.\n\nThis will digitally sign your system firmware.", + "ja": "重要なパスワード要求\nSYSTEM UPDATEのパスフレーズを入力してください。\n\nこれにより、システムのファームウェアに電子署名が施されます。", "zh": "输入密码 软件更新 安全含义:至关重要 ", "en-audio": "Enter update password, in order to authorize a gateware update." }, "rootkeys.signxous.finished": { "en": "Xous signing finished.\nReboot at your earliest convenience.", + "ja": "Xousのサインは終了しました。ご都合の良い時に再起動してください。", "zh": "更新完成重启应用", "en-audio": "Xous signing finished. Reboot at your earliest convenience." }, "rootkeys.get_login_password": { "en": "Password request\nEnter the 'DEVICE UNLOCK' PIN code.", + "ja": "パスワード要求\nデバイスのロック解除のPINコードを入力してください。", "zh": "输入密码 解锁 安全含义:低", "en-audio": "Enter device unlock password to access basic service." }, "rootkeys.bad_password_request": { "en": "Someone issued a request for a non-existent password.", + "ja": "誰かが存在しないパスワードのリクエストを発行しました。", "zh": "**improve**无效的密码请求", "en-audio": "Someone issued a request for a non-existent password." }, "rootkeys.policy_request": { "en": "Please pick a password retention policy:", + "ja": "パスワード保持ポリシーを指定ください。", "zh": "请选择密码保留策略:", "en-audio": "Please pick a passowrd retention policy." }, "rootkeys.policy_clear": { "en": "Clear after use", + "ja": "使用後クリア", "zh": "使用后删除", "en-audio": "Clear password after use" }, "rootkeys.policy_suspend": { "en": "Retain until sleep", + "ja": "スリープまで保持", "zh": "睡眠后删除", "en-audio": "Retain password until sleep" }, "rootkeys.policy_idle": { "en": "Retain until timeout", + "ja": "タイムアウトまで保持", "zh": "保留到延时", "en-audio": "Retain until timeout" }, "rootkeys.policy_keep": { "en": "Retain until reboot", + "ja": "リブートまで保持", "zh": "保留到启动", "en-audio": "Retain until reboot" } diff --git a/services/root-keys/src/lib.rs b/services/root-keys/src/lib.rs index f720fd1cf..507e8672f 100644 --- a/services/root-keys/src/lib.rs +++ b/services/root-keys/src/lib.rs @@ -29,7 +29,7 @@ pub struct RootKeys { } impl RootKeys { pub fn new(xns: &xous_names::XousNames, key_index: Option) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_KEYS).expect("Can't connect to Keys server"); let index = if let Some(ki) = key_index { ki @@ -178,8 +178,7 @@ impl Drop for RootKeys { // the connection to the server side must be reference counted, so that multiple instances of this object within // a single process do not end up de-allocating the CID on other threads before they go out of scope. // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/shellchat/src/cmds/net_cmd.rs b/services/shellchat/src/cmds/net_cmd.rs index 859b6168f..47f4eb5b8 100644 --- a/services/shellchat/src/cmds/net_cmd.rs +++ b/services/shellchat/src/cmds/net_cmd.rs @@ -4,10 +4,13 @@ use net::{Duration, XousServerId, NetPingCallback}; use xous::MessageEnvelope; use num_traits::*; use std::net::{SocketAddr, IpAddr}; +use std::io::Write; +use std::io::Read; pub struct NetCmd { udp: Option, udp_clone: Option, + tcp_listener: Option, callback_id: Option, callback_conn: u32, udp_count: u32, @@ -19,6 +22,7 @@ impl NetCmd { NetCmd { udp: None, udp_clone: None, + tcp_listener: None, callback_id: None, callback_conn: xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap(), udp_count: 0, @@ -30,8 +34,9 @@ impl NetCmd { #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub(crate) enum NetCmdDispatch { - UdpTest1 = 0x1_0000, // we're muxing our own dispatch + ping dispatch, so we need a custom discriminant - UdpTest2 = 0x1_0001, + UdpTest1 = 0x1_0000, // we're muxing our own dispatch + ping dispatch, so we need a custom discriminant + UdpTest2 = 0x1_0001, + TcpServer = 0x2_0000, } pub const UDP_TEST_SIZE: usize = 64; @@ -54,8 +59,6 @@ impl<'a> ShellCmdApi<'a> for NetCmd { if let Some(sub_cmd) = tokens.next() { match sub_cmd { "tcpget" => { - use std::io::Write; - use std::io::Read; // note: to keep shellchat lightweight, we do a very minimal parsing of the URL. We assume it always has // a form such as: // bunniefoo.com./bunnie/test.txt @@ -111,6 +114,19 @@ impl<'a> ShellCmdApi<'a> for NetCmd { write!(ret, "Usage: tcpget bunniefoo.com/bunnie/test.txt").unwrap(); } } + "server" => { + let mut listener = net::TcpListener::bind_xous( + "127.0.0.1:80" + ).unwrap(); + listener.set_scalar_notification( + self.callback_conn, + self.callback_id.unwrap() as usize, + [Some(NetCmdDispatch::TcpServer.to_usize().unwrap()), None, None, None] + ); + // listener.set_nonblocking(true).unwrap(); // we shouldn't need to block because we only check once we're notified + self.tcp_listener = Some(listener); + write!(ret, "TCP listener started on port 80").unwrap(); + } // Testing of udp is done with netcat: // to send packets run `netcat -u 6502` on a remote host, and then type some data // to receive packets, use `netcat -u -l 6502`, on the same remote host, and it should show a packet of counts received @@ -228,7 +244,7 @@ impl<'a> ShellCmdApi<'a> for NetCmd { } - fn callback(&mut self, msg: &MessageEnvelope, _env: &mut CommonEnv) -> Result>, xous::Error> { + fn callback(&mut self, msg: &MessageEnvelope, env: &mut CommonEnv) -> Result>, xous::Error> { use core::fmt::Write; log::debug!("net callback"); @@ -298,6 +314,69 @@ impl<'a> ShellCmdApi<'a> for NetCmd { write!(ret, "Got NetCmd callback from uninitialized socket").unwrap(); } }, + Some(NetCmdDispatch::TcpServer) => { + if let Some(listener) = &mut self.tcp_listener { + match listener.accept() { + Ok((mut stream, addr)) => { + let test_string = std::format!("Hello from Precursor!\n\rI have been up for {} ms.\n\r", env.ticktimer.elapsed_ms()); + let mut request = [0u8; 1024]; + match stream.read(&mut request) { + Ok(len) => { + let r = std::string::String::from_utf8_lossy(&request[..len]); + log::info!("Request received from {:?}: {}", stream.peer_addr().unwrap(), r); + write!(ret, "{}\n\n", r).unwrap(); + let mut tokens = r.split(' '); + let mut valid = true; + if let Some(verb) = tokens.next() { + if verb != "GET" { + log::info!("Expected GET, got {}", verb); + valid = false; + } + } + if let Some(path) = tokens.next() { + if path != "/" { + log::info!("We only know /, got {}", path); + valid = false; + } + } + if valid { + // now send a page back... + let page = format!("HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\n\rContent-Length: {}\n\rConnection: close\n\r\n\r{}\n\r", + test_string.len(), + test_string); + log::info!("Responding with: {}", page); + write!(stream, "{}", page).unwrap(); + log::info!("Flushing response to {:?}", addr); + stream.flush().unwrap(); + log::info!("Sent a response {:?}", addr); + write!(ret, "Sent 200 to {:?}", addr).unwrap(); + } else { + let errstring = "Sorry, I have only one trick, and it's pretty dumb."; + let notfound = format!("HTTP/1.1 404 Not Found\n\rConnection: close\n\rContent-Type: text/plain; charset=utf-8\n\rContent-Length: {}\n\r\n\r{}\n\r", + errstring.len(), + errstring + ); + log::info!("Responding with: {}", notfound); + write!(stream, "{}", notfound).unwrap(); + stream.flush().unwrap(); + write!(ret, "Sent 404 to {:?}", addr).unwrap(); + } + } + Err(e) => { + log::info!("Stream was opened, but no request received: {:?}", e); + write!(ret, "Socket opened but no request data received: {:?}", e).unwrap(); + } + } + // stream should close automatically as `stream` goes out of scope here and Drop is called. + } + Err(e) => { + write!(ret, "Got error on TCP accept: {:?}", e).unwrap(); + } + } + } else { + write!(ret, "Got NetCmd callback for uninitialized server").unwrap(); + } + }, None => { // rebind the scalar args to the Ping convention let op = arg1; diff --git a/services/skeleton/src/lib.rs b/services/skeleton/src/lib.rs index 15b2ce66c..49f1532ce 100644 --- a/services/skeleton/src/lib.rs +++ b/services/skeleton/src/lib.rs @@ -9,7 +9,7 @@ pub struct Codec { } impl Codec { pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_CODEC).expect("Can't connect to Codec server"); Ok(Codec { conn @@ -24,8 +24,7 @@ impl Drop for Codec { // the connection to the server side must be reference counted, so that multiple instances of this object within // a single process do not end up de-allocating the CID on other threads before they go out of scope. // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), diff --git a/services/spinor/src/lib.rs b/services/spinor/src/lib.rs index dabe983e6..7c0a46c8e 100644 --- a/services/spinor/src/lib.rs +++ b/services/spinor/src/lib.rs @@ -32,7 +32,7 @@ impl Spinor { #[cfg(not(test))] pub fn new(xns: &xous_names::XousNames) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_SPINOR).expect("Can't connect to Spinor server"); let trng = trng::Trng::new(&xns).expect("Can't connect to TRNG servere"); @@ -396,8 +396,7 @@ impl Drop for Spinor { // the connection to the server side must be reference counted, so that multiple instances of this object within // a single process do not end up de-allocating the CID on other threads before they go out of scope. // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), diff --git a/services/status/locales/i18n.json b/services/status/locales/i18n.json index 25edffc78..98852b165 100644 --- a/services/status/locales/i18n.json +++ b/services/status/locales/i18n.json @@ -1,122 +1,146 @@ { "stats.measuring": { + "ja": "測定...", "en": "Measuring...", "zh": "进行测量...", "en-audio": "Measuring..." }, "stats.disconnected": { + "ja": "接続不可", "en": "Not connected", "zh": "没有连接", "en-audio": "Not connected" }, "stats.uptime": { "translator-note": "This needs to be a very short string, 2 chars max. Trailing space is necessary for English due to proportional font.", + "ja": "稼働 ", "en": "Up ", - "zh": "运行", + "zh": "运行 ", "en-audio": "Uptime" }, "secnote.usb_unlock": { "en": " USB unlocked", + "ja": "USBロック解除", "zh": "USB解锁", "en-audio": "USB unlocked" }, "secnote.gateware_fail": { "en": " Gateware selfsig fail", + "ja": "Gateware selfsig 失敗", "zh": "比特流签名失败", "en-audio": "Gateware self signature failure" }, "secnote.state_fail": { "en": " Invalid key state", + "ja": "無効なキー状態", "zh": "无效的根密钥", "en-audio": "Invalid key state" }, "secnote.no_keys": { "en": " Root keys uninitialized", + "ja": "ルートキーは未初期化", "zh": "密钥未初始化", "en-audio": "Root keys unitialized" }, "secnote.allclear": { "en": " No security warnings", + "ja": "セキュリティ警告なし", "zh": "没有警告", "en-audio": "🔇" }, "secnote.startup": { "en": " Starting up...", + "ja": "起動中...", "zh": "现在开始...", "en-audio": "🔇" }, "mainmenu.sleep": { "en": "Sleep now", + "ja": "今睡眠", "zh": "睡眠模式", "en-audio": "Sleep now" }, "mainmenu.backlighton": { "en": "Backlight on", + "ja": "バックライト点灯", "zh": "背光开启", "en-audio": "🔇" }, "mainmenu.backlightoff": { "en": "Backlight off", + "ja": "バックライト消灯", "zh": "背光关闭", "en-audio": "🔇" }, "mainmenu.init_keys": { "en": "Initialize root keys", + "ja": "ルートキーの初期化", "zh": "设置根密码", "en-audio": "Initialize root keys" }, "mainmenu.provision_gateware": { "en": "Install gateware update", + "ja": "ゲートウェアアップデートをインストールする", "zh": "安装比特流更新", "en-audio": "Install gateware update" }, "mainmenu.selfsign": { "en": "Sign Xous update", + "ja": "サインXousアップデート", "zh": "数字签名Xous", "en-audio": "Sign Xous update" }, "mainmenu.set_rtc": { "en": "Set time", + "ja": "時間設定", "zh": "设置时间", "en-audio": "Set time" }, "mainmenu.pddb": { "en": "PDDB Submenu", + "ja": "PDDBサブメニュー", "zh": "PDDB子菜单", "en-audio": "PDDB submenu" }, "mainmenu.app": { "en": "Switch to App...", + "ja": "アプリに切り替わる...", "zh": "APP子菜单", "en-audio": "Switch to app" }, "mainmenu.reboot": { "en": "Reboot", + "ja": "リブート", "zh": "重启", "en-audio": "Reboot" }, "mainmenu.closemenu": { "en": "Close menu", + "ja": "メニューを閉じる", "zh": "关闭功能表", "en-audio": "Close menu" }, "mainmenu.cant_sleep": { "en": "Can't sleep while charging", + "ja": "充電中は眠れません", "zh": "充电时睡不着", "en-audio": "Can't sleep while charging" }, "appmenu.ball": { "en": "Simple ball demo", + "ja": "シンプルなボールのデモ", "zh": "简单的球演示", "en-audio": "Simple ball demo" }, "appmenu.repl": { "en": "Basic REPL demo", + "ja": "シンプルなREPLデモ", "zh": "基本 REPL 演示", "en-audio": "Basic REPL demo" }, "appmenu.shellchat": { "en": "Shellchat", + "ja": "Shellchat", "zh": "外壳聊天", "en-audio": "Shellchat" } diff --git a/services/status/src/main.rs b/services/status/src/main.rs index 73bca1647..0d4f99426 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -197,7 +197,7 @@ fn xmain() -> ! { uptime_tv.style = GlyphStyle::Regular; uptime_tv.draw_border = false; uptime_tv.margin = Point::new(3, 0); - write!(uptime_tv, "Booting up...").expect("|status: couldn't init uptime text"); + write!(uptime_tv, "{}", t!("secnote.startup", xous::LANG)).expect("|status: couldn't init uptime text"); gam.post_textview(&mut uptime_tv) .expect("|status: can't draw battery stats"); log::trace!("|status: screensize as reported: {:?}", screensize); diff --git a/services/susres/src/lib.rs b/services/susres/src/lib.rs index 6bf732b37..5fa89b85c 100644 --- a/services/susres/src/lib.rs +++ b/services/susres/src/lib.rs @@ -19,7 +19,7 @@ pub struct Susres { impl Susres { #[cfg(any(target_os = "none", target_os = "xous"))] pub fn new(order: Option, xns: &xous_names::XousNames, cb_discriminant: u32, cid: CID) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_SUSRES).expect("Can't connect to SUSRES"); let execution_gate_conn = xns.request_connection_blocking(api::SERVER_NAME_EXEC_GATE).expect("Can't connect to the execution gate"); @@ -49,7 +49,7 @@ impl Susres { // during boot when all the hosted mode servers try to connect. This isn't an issue on real hardware. #[cfg(not(any(target_os = "none", target_os = "xous")))] pub fn new(_ordering: Option, xns: &xous_names::XousNames, cb_discriminant: u32, cid: CID) -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); Ok(Susres { conn: 0, suspend_cb_sid: None, @@ -147,8 +147,7 @@ impl Drop for Susres { if let Some(sid) = self.suspend_cb_sid.take() { drop_conn(sid); } - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe{xous::disconnect(self.conn).unwrap();} } } diff --git a/services/ticktimer-server/src/lib.rs b/services/ticktimer-server/src/lib.rs index a303bb10a..7ae3a106d 100644 --- a/services/ticktimer-server/src/lib.rs +++ b/services/ticktimer-server/src/lib.rs @@ -11,7 +11,7 @@ pub struct Ticktimer { } impl Ticktimer { pub fn new() -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xous::connect(xous::SID::from_bytes(b"ticktimer-server").unwrap())?; Ok(Ticktimer { conn }) } @@ -76,8 +76,7 @@ static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for Ticktimer { fn drop(&mut self) { // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe { xous::disconnect(self.conn).unwrap(); } diff --git a/services/ticktimer-server/src/main.rs b/services/ticktimer-server/src/main.rs index 561b55f9c..0fe3a7bb3 100644 --- a/services/ticktimer-server/src/main.rs +++ b/services/ticktimer-server/src/main.rs @@ -475,7 +475,7 @@ fn xmain() -> ! { log::info!("****************************************************************"); log::info!("Welcome to Xous {}", version::SEMVER); - log::info!("Built at {}", version::TIMESTAMP); + log::info!("Built on {}", version::TIMESTAMP); log::info!("****************************************************************"); let ticktimer_server = xous::create_server_with_address(b"ticktimer-server") diff --git a/services/trng/src/lib.rs b/services/trng/src/lib.rs index 61d58f76c..ebbc83cc3 100644 --- a/services/trng/src/lib.rs +++ b/services/trng/src/lib.rs @@ -15,7 +15,7 @@ impl Trng { let conn = xns .request_connection_blocking(api::SERVER_NAME_TRNG) .expect("Can't connect to TRNG server"); - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); Ok(Trng { conn, error_sid: None, @@ -124,8 +124,7 @@ static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for Trng { fn drop(&mut self) { // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe { xous::disconnect(self.conn).unwrap(); } diff --git a/services/xous-names/src/lib.rs b/services/xous-names/src/lib.rs index 92af0dfbc..9d4af65cf 100644 --- a/services/xous-names/src/lib.rs +++ b/services/xous-names/src/lib.rs @@ -16,7 +16,7 @@ pub struct XousNames { } impl XousNames { pub fn new() -> Result { - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + REFCOUNT.fetch_add(1, Ordering::Relaxed); let conn = xous::connect(xous::SID::from_bytes(b"xous-name-server").unwrap()) .expect("Couldn't connect to XousNames"); Ok(XousNames { conn }) @@ -175,8 +175,7 @@ static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for XousNames { fn drop(&mut self) { // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. - REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) - 1, Ordering::Relaxed); - if REFCOUNT.load(Ordering::Relaxed) == 0 { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { unsafe { xous::disconnect(self.conn).unwrap(); }