HackMD 筆記匯出摘要:42 篇工程筆記的主題導讀HackMD Export Digest: a Thematic Reader for 42 Engineering NotesHackMD エクスポート要約:42 本のエンジニアリングノートをテーマ別に読む

這一頁把一份 HackMD 使用者匯出(42 篇 Markdown 筆記)整理成七個主題:慣性感測與姿態估計、邊坡監測「種子」計畫、公車與緊急車輛號誌優先的路側單元程式碼、計算機結構與並行、PIM 與 NVM 檔案系統論文、作業系統與 RTOS 課程,以及 C 語言、工具與外包案。每一節說明筆記在談什麼、記下了哪些公式與數據、留下了哪些未解的問題。文末附全部 42 篇的索引表。This page reads a HackMD user export of 42 Markdown notes as seven themes: inertial sensing and attitude estimation, a slope-monitoring sensor "seed" project, roadside-unit code for bus and emergency-vehicle signal priority, computer architecture and concurrency, processing-in-memory and NVM file-system papers, OS and RTOS coursework, and C language, tooling and freelance work. Each section explains what the notes are about, which formulas and numbers they record, and which questions they left open. A full index of all 42 notes closes the page.このページは HackMD ユーザーエクスポート(Markdown ノート 42 本)を七つのテーマで読み解く:慣性センシングと姿勢推定、斜面監視センサ「シード」計画、バス・緊急車両の信号優先を担う路側機のコード、計算機構成と並行処理、PIM と NVM ファイルシステムの論文、OS と RTOS の講義、そして C 言語・ツール・フリーランス案件。各節でノートの主題、記録された式や数値、未解決のまま残った問いを説明し、末尾に全 42 本の索引表を置く。

總覽:這份匯出是什麼Overview: what this export is概要:このエクスポートとは何か

本頁整理的是一份 HackMD 使用者匯出檔:42 篇 Markdown 筆記,筆記本文合計約 190 KB(壓縮檔連同附檔約 210 KB)。全部出自同一位工程師之手,寫作期間大致落在 2020 到 2022 年,當時他一邊在大學實驗室做研究計畫,一邊接外包案和準備考試。這些筆記從來不是為了給別人看而寫的,而是作者的工作草稿:讀論文的摘記、會議的即時紀錄、程式碼片段、待讀連結,以及大量還沒有答案的問題。This page digests a HackMD user export: 42 Markdown notes, about 190 KB of note text (roughly 210 KB with the archive overhead). All of them were written by one engineer, mostly between 2020 and 2022, while he worked on research projects in a university lab and took on freelance cases and exam preparation on the side. The notes were never meant for an audience. They are working scratch: paper summaries, live meeting minutes, code fragments, links to read later, and many questions that had not been answered yet.このページは HackMD のユーザーエクスポートをまとめたものだ。42 本の Markdown ノート、本文合計で約 190 KB(アーカイブ全体では約 210 KB)。すべて一人のエンジニアが、おおむね 2020 年から 2022 年にかけて、大学の研究室でプロジェクトに携わりながら副業の受託案件や試験準備を並行していた時期に書いたものである。読者を想定して書かれたノートは一本もない。論文の要約、会議のその場のメモ、コード断片、あとで読むリンク、そして未解決の疑問が大量に残った作業用の下書きだ。

筆記如何被組織:front-matter 與標籤How the notes are organised: front-matter and tagsノートの整理方法:front-matter とタグ

來源筆記:Source notes: 出典ノート:ahrs.md, freeRTOS.md, Talk slides template.md, 邊坡種子.md

每篇筆記開頭都是 HackMD 的 YAML front-matter,只有兩個欄位:title: 和 tags:。有標籤的筆記會在正文第一行再以 ###### tags: 重複一次,這是 HackMD 舊版的習慣寫法。實際用到的標籤只有十個:訊號處理(6 篇)、paper(3)、pim(2)、rtos(2)、會議記錄(2)、外包案(2)、課程(1)、資格考(1)、linux related(1)、Templates(1,另附一個 Talk 子標籤)。42 篇裡有 23 篇完全沒有標籤,也就是超過一半。標籤系統顯然是事後才補的,而且只補到一半;因此本頁不依賴原始標籤,而是依內容重新分成七個主題。Every note opens with HackMD's YAML front-matter, which here carries only two fields: title: and tags:. Tagged notes repeat the tags on the first body line as ###### tags:, the older HackMD convention. Only ten tags were ever used: 訊號處理 (signal processing, 6 notes), paper (3), pim (2), rtos (2), 會議記錄 (meeting minutes, 2), 外包案 (freelance cases, 2), 課程 (coursework, 1), 資格考 (qualifying exam, 1), linux related (1) and Templates (1, with a Talk sub-tag). Twenty-three of the 42 notes, more than half, carry no tag at all. The tagging was clearly added after the fact and never finished, so this page does not rely on it. It regroups the notes into seven themes by content instead.各ノートは HackMD の YAML front-matter で始まり、フィールドは title: と tags: の二つだけである。タグ付きのノートは本文一行目に ###### tags: としてタグを繰り返す。これは旧 HackMD の慣習だ。実際に使われたタグは十個しかない。訊號處理(信号処理、6 本)、paper(3)、pim(2)、rtos(2)、會議記錄(会議メモ、2)、外包案(受託案件、2)、課程(授業、1)、資格考(資格試験、1)、linux related(1)、Templates(1、Talk のサブタグ付き)。42 本のうち 23 本、つまり半分以上にはタグが一切ない。タグ付けは明らかに後付けで、しかも途中で止まっている。そのためこのページは元のタグに頼らず、内容に基づいて七つのテーマに再分類した。

篇幅分布:兩篇巨無霸與一長串連結便條Size distribution: two giants and a long tail of link stashesサイズ分布:二本の巨大ノートと大量のリンクメモ

來源筆記:Source notes: 出典ノート:智慧交通的code.md, 邊坡種子.md, NOVA file system.md, 姿態估計.md, 汽車音響.md, nuttx.md

篇幅極不平均。兩篇筆記就佔了將近一半的總量:智慧交通的code.md(47.7 KB,幾乎全是貼上的 C 程式碼)和 邊坡種子.md(42.4 KB,兩年份的週會紀錄)。接下來是 NOVA file system.md(12.9 KB)和 姿態估計.md(11.1 KB),其餘全部在 9 KB 以下。中位數只有 1.4 KB;18 篇不到 1 KB,其中好幾篇只是一個標題加一、兩個網址,例如 汽車音響.md(92 bytes,一條部落格連結)和 nuttx.md(一條 Medium 教學連結)。這類筆記是書籤夾,不是文章;後面的主題章節會把它們當成連結便條,並指出哪些是值得保留的公開參考資料。The sizes are very uneven. Two notes hold almost half of the total: 智慧交通的code.md (47.7 KB, almost entirely pasted C source) and 邊坡種子.md (42.4 KB, two years of weekly meeting minutes). Next come NOVA file system.md (12.9 KB) and 姿態估計.md (11.1 KB); everything else is under 9 KB. The median note is only 1.4 KB, and 18 notes are under 1 KB. Several of those are just a title and one or two URLs, such as 汽車音響.md (92 bytes, one blog link) and nuttx.md (one Medium tutorial link). These are bookmarks, not articles. The theme sections below treat them as link stashes and point out which links are public references worth keeping.サイズは極端に偏っている。二本のノートだけで全体のほぼ半分を占める。智慧交通的code.md(47.7 KB、ほぼ全部が貼り付けた C ソース)と 邊坡種子.md(42.4 KB、二年分の週次会議メモ)だ。次に NOVA file system.md(12.9 KB)と 姿態估計.md(11.1 KB)が続き、残りはすべて 9 KB 未満である。中央値はわずか 1.4 KB で、18 本は 1 KB に満たない。その多くはタイトルと URL が一つか二つあるだけで、たとえば 汽車音響.md(92 バイト、ブログリンク一本)と nuttx.md(Medium のチュートリアル一本)がそうだ。これらは記事ではなくブックマークである。以降のテーマ節ではリンクメモとして扱い、残す価値のある公開参考資料がどれかを示す。

圖:42 篇筆記的大小(KB),依本頁七個主題分組,組內由大到小排列。把游標移到長條上可看檔名、主題、標籤與位元組數;完整數字見文末索引表。Figure: size of each of the 42 notes in kilobytes, grouped by the seven themes of this page and sorted within each group. Hover a bar for the filename, theme, tags and byte count; the index table at the end carries the full numbers.図:42 本のノートの大きさ(KB)。本ページの七つのテーマで分類し、各テーマ内は大きい順に並べた。バーにカーソルを置くとファイル名・テーマ・タグ・バイト数を表示する。正確な数値は末尾の索引表を参照。
Size of each of the 42 notes in kilobytes, grouped by theme 0 10 20 30 40 50 KBKBKB 慣性感測與姿態估計Inertial sensing and attitude慣性センシングと姿勢推定 · 5 姿態估計.md 10.8 ahrs.md 6.1 kalman filter.md 3.0 位移計算.md 2.6 四元數.md 2.0 邊坡種子計畫Slope-seed project斜面シード計画 · 2 邊坡種子.md 41.4 lora.md 智慧運輸(TSP/EVSP)Smart transport (TSP / EVSP)スマート交通(TSP/EVSP) · 5 智慧交通的code.md 46.6 智慧運輸.md 3.1 致翰交接.md rsu checklist.md 交接文件格式.md 計算機結構與並行Architecture and concurrency計算機構成と並行処理 · 9 mesi protocol(也稱為伊利諾斯協議,是因為該… 3.6 dma cache coherence.md 3.0 計算機結構筆記.md 同步.md concurrency and parallism_ 並行和多執行緒程… continous runahead_ transparent hardware a… 資料結構與演算法.md rcu related;lock free.md pipeline.md PIM 與 NVM 論文PIM and NVM papersPIM と NVM の論文 · 4 NOVA file system.md 12.6 a processing-in-memory architecture progra… 8.4 一些linux file system的屬性.md 2.2 paper report of others.md 作業系統/RTOS/LinuxOS, RTOS and LinuxOS・RTOS・Linux · 9 rtos課程筆記.md 6.7 作業系統筆記.md 4.5 problem answered by chatgpt.md 3.4 epoll system call.md 待看文件.md linux bsp and cpu and porting.md 自幹系列文章.md nuttx.md freeRTOS.md C 語言、工具與外包案C, tools and freelanceC 言語・ツール・案件 · 8 太陽能儲能公司.md 4.9 c語言好文.md 4.2 Talk slides template.md 2.4 工作日誌.md 呼叫師傅 軟體規格討論.md matlab.md 資格考.md 汽車音響.md

寫作風格:中英夾雜、滿篇問號、消失的截圖Writing style: mixed zh/en, open questions, vanished screenshots文体:中英混在、疑問符だらけ、消えたスクリーンショット

來源筆記:Source notes: 出典ノート:姿態估計.md, 邊坡種子.md, a processing-in-memory architecture programming paradigm for wireless IOT applications.md, 工作日誌.md, c語言好文.md

四個特徵貫穿全部筆記。第一,中英夾雜:術語和程式識別字保留英文,解釋和感想用中文,句子常在半途換語言。第二,問號:全部筆記合計出現 65 處「??」,標記作者當下不懂或打算回頭查的地方,例如「gateway??(樹莓pi?)」;本頁把這些整理成每個主題的未解問題。第三,截圖:14 篇筆記嵌了 179 張 imgur 圖片,論文筆記和姿態估計筆記尤其密集。匯出檔只保留網址,圖片沒有一起匯出,多數連結已失效;本頁只描述圖片原本的內容。第四,刪除線:待辦項目做完就用 ~~ 畫掉,見於 工作日誌.md、邊坡種子.md、c語言好文.md 等五篇,可以看出哪些事真的做完了。Four habits run through every note. First, mixed languages: technical terms and identifiers stay in English, explanations and reactions are in Chinese, and sentences often switch halfway. Second, question marks: the notes contain 65 occurrences of "??", marking what the author did not understand or meant to look up later, for example "gateway?? (Raspberry Pi?)"; this page collects those as the open questions of each theme. Third, screenshots: 14 notes embed 179 imgur images, densest in the paper notes and the attitude-estimation note. The export keeps only the URLs, the images were not exported, and most links are dead by now; this page describes what each figure showed instead. Fourth, strikethrough: to-do items are crossed out with ~~ when done, in five notes including 工作日誌.md, 邊坡種子.md and c語言好文.md, which tells a reader which tasks were actually finished.全ノートに共通する癖が四つある。第一に言語の混在。専門用語と識別子は英語のまま、説明と感想は中国語で、文の途中で言語が切り替わることも多い。第二に疑問符。全ノートで「??」が 65 箇所あり、当時理解できなかった点やあとで調べるつもりだった点に付けられている。例として「gateway??(樹莓pi?)」。このページではそれらを各テーマの未解決の疑問としてまとめた。第三にスクリーンショット。14 本のノートに 179 枚の imgur 画像が埋め込まれ、論文ノートと姿勢推定ノートで特に密度が高い。エクスポートには URL だけが残り、画像は含まれず、リンクの多くはすでに切れている。このページは各図が何を示していたかを文章で説明する。第四に取り消し線。やることリストの完了項目は ~~ で消され、工作日誌.md、邊坡種子.md、c語言好文.md など五本に見られる。どの作業が実際に終わったかが読み取れる。

讀這些筆記時,「??」比結論更有價值:它們是作者當時的真實疑問,而本頁各主題末尾的未解問題清單正是從這 65 個問號整理出來的。When reading these notes, the "??" marks are worth more than the conclusions: they are the author's real questions at the time, and the open-question lists at the end of each theme below are built from those 65 marks.これらのノートを読むとき、「??」は結論より価値がある。当時の作者の本当の疑問であり、以下の各テーマ末尾にある未解決の疑問リストはこの 65 箇所から組み立てたものだ。

七個主題與本頁的結構The seven themes and how this page is organised七つのテーマとこのページの構成

來源筆記:Source notes: 出典ノート:listing.txt

每篇筆記恰好歸入一個主題。兩個主題是實驗室計畫(邊坡監測種子計畫、智慧運輸號誌優先),一個是感測訊號處理(慣性感測與姿態估計),三個是讀書筆記(計算機結構與並行、PIM 與 NVM 檔案系統論文、作業系統與 Linux 內部),最後一個收納 C 語言、MATLAB、範本、外包案與個人規劃。本頁依此順序各給一節,最後附上全部 42 篇的索引表。Each note belongs to exactly one theme. Two themes are lab projects (the slope-monitoring seed project and smart-transport signal priority), one is sensor signal processing (inertial sensing and attitude estimation), three are study notes (computer architecture and concurrency, PIM and NVM file-system papers, OS and Linux internals), and the last gathers C language, MATLAB, templates, freelance cases and personal planning. The page gives one section to each theme in this order and ends with an index table of all 42 notes.各ノートはちょうど一つのテーマに属する。二つは研究室のプロジェクト(斜面監視シードプロジェクトとスマート交通の信号優先)、一つはセンサ信号処理(慣性センシングと姿勢推定)、三つは学習ノート(計算機アーキテクチャと並行処理、PIM と NVM ファイルシステム論文、OS と Linux 内部)、最後の一つは C 言語、MATLAB、テンプレート、受託案件、個人の計画をまとめる。ページはこの順に各テーマへ一節ずつ割き、最後に全 42 本の索引表を置く。

主題Themeテーマ 篇數Notes本数 合計 bytesTotal bytes合計バイト 佔比Share割合 最大的一篇Largest note最大のノート
1 慣性感測與姿態估計1 Inertial sensing and attitude estimation1 慣性センシングと姿勢推定525,13513.2 %姿態估計.md
2 邊坡監測種子計畫2 Slope-monitoring seed project2 斜面監視シードプロジェクト242,76822.4 %邊坡種子.md
3 智慧運輸與號誌優先3 Smart transportation and signal priority3 スマート交通と信号優先553,13127.8 %智慧交通的code.md
4 計算機結構與並行4 Computer architecture and concurrency4 計算機アーキテクチャと並行処理911,2675.9 %mesi protocol….md
5 PIM 與 NVM 檔案系統論文5 PIM and NVM file-system papers5 PIM と NVM ファイルシステム論文425,36313.3 %NOVA file system.md
6 作業系統、RTOS 與 Linux 內部6 OS, RTOS and Linux internals6 OS、RTOS、Linux 内部917,7759.3 %rtos課程筆記.md
7 C、MATLAB、範本、外包案與規劃7 C, MATLAB, templates, freelance and planning7 C、MATLAB、テンプレート、受託、計画815,6548.2 %太陽能儲能公司.md
合計Total合計42191,093100 %

表中的比例清楚顯示:以位元組計,兩個實驗室計畫(主題二、三)就佔了一半,而筆記篇數最多的主題四和六,其實多半是短短的讀書便條。The shares make one thing clear: by bytes, the two lab projects (themes 2 and 3) account for half the export, while themes 4 and 6, which have the most notes, are mostly short study jottings.割合を見ると一つはっきりする。バイト数では研究室の二つのプロジェクト(テーマ 2 と 3)がエクスポートの半分を占め、ノート数が最も多いテーマ 4 と 6 はほとんどが短い学習メモである。

這份公開摘要刻意省略了什麼What this public digest deliberately leaves outこの公開ダイジェストが意図的に省いたもの

來源筆記:Source notes: 出典ノート:智慧交通的code.md, 邊坡種子.md, 呼叫師傅 軟體規格討論.md, 致翰交接.md

原始筆記是私人工作紀錄,裡面有不該公開的東西。本頁省略了五類內容:一是登入憑證(資料庫與網頁主控台的登入資訊,主要出現在智慧運輸的程式碼筆記和外包案討論裡);二是主機資訊(IP 位址、跳板指令、路口 RSU 編號與位址的對應);三是人名(同學、學生、教授、廠商窗口、公部門承辦人一律改以角色稱呼,例如「指導教授」、「負責中介軟體的同學」,機構名稱則保留);四是私人雲端連結(Google Drive、OneDrive、同學的 HackMD 筆記);五是截圖。理由很簡單:這些對理解技術內容沒有幫助,卻會讓當事人暴露在風險裡。保留下來的是方法、參數、量測數字和作者的思考過程。The raw notes are a private work record and contain things that must not be published. This page omits five kinds of content: login credentials (database and web-console secrets, found mostly in the smart-transport code note and the freelance discussion); host details (IP addresses, jump-host commands, the mapping from intersection RSU IDs to addresses); names of individuals (labmates, students, professors, vendor contacts and officials appear by role only, such as "the advisor" or "the labmate who owned the middleware", while institution names are kept); private cloud links (Google Drive, OneDrive, teammates' HackMD notes); and screenshots. The reason is simple: none of this helps a reader understand the technical content, and all of it would expose the people involved. What remains is the methods, the parameters, the measured numbers and the author's line of thought.元のノートは私的な作業記録で、公開してはならないものを含む。このページは五種類の内容を省いた。ログイン認証情報(データベースとウェブコンソールの秘密情報。主にスマート交通のコードノートと受託案件の議論にある)、ホスト情報(IP アドレス、踏み台コマンド、交差点 RSU の ID とアドレスの対応)、個人名(同僚、学生、教授、ベンダー担当者、役所の担当者は「指導教員」「ミドルウェアを担当していた同僚」のように役割だけで呼び、機関名は残す)、私的なクラウドリンク(Google Drive、OneDrive、仲間の HackMD ノート)、そしてスクリーンショットだ。理由は単純で、これらは技術内容の理解に役立たず、関係者を危険にさらすだけである。残したのは手法、パラメータ、測定値、そして作者の思考の筋道だ。

回到頂端 ↑Back to top ↑ページ上部へ ↑

慣性感測與姿態估計:用低價 IMU 分辨滑動、振動與旋轉Inertial sensing and attitude estimation: telling sliding from vibration with low-cost IMUs慣性センシングと姿勢推定:安価な IMU で滑動・振動・回転を見分ける

五篇「訊號處理」筆記(ahrs.md、四元數.md、kalman filter.md、姿態估計.md、位移計算.md)記錄作者在 2021 年 1 月前後自學 IMU 的過程:從幾十元的 MPU-6050 / MPU-9250 出發,最後考慮自帶融合的 Bosch BNO055 與工業級的 ADIS16467。內容多半是連結與截圖,夾雜作者自己的推導、程式片段、數值驗證與大量「??」。本節依主題整理。Five "signal processing" notes (ahrs.md, 四元數.md, kalman filter.md, 姿態估計.md, 位移計算.md) record the author teaching himself IMUs around January 2021, starting from the few-dollar MPU-6050 and MPU-9250 and ending with the Bosch BNO055 (on-chip fusion) and the industrial ADIS16467 under consideration. Most of the material is links and screenshots, interleaved with his own derivations, code fragments, numeric checks and many "??" marks. This section groups it by theme.「訊號處理」の五つのノート(ahrs.md、四元數.md、kalman filter.md、姿態估計.md、位移計算.md)は、2021 年 1 月前後に著者が IMU を独学した過程を記録する。数百円の MPU-6050 / MPU-9250 から始め、最後はオンチップ融合の Bosch BNO055 と産業グレードの ADIS16467 を検討するに至る。内容の大半はリンクとスクリーンショットで、著者自身の導出、コード断片、数値検証、大量の「??」が挟まる。本節はテーマ別に整理する。

動機:邊坡監測要分辨滑動、振動與旋轉Why: slope monitoring must separate sliding, vibration and rotation動機:斜面監視で滑動・振動・回転を分ける

來源筆記:Source notes: 出典ノート:姿態估計.md, 位移計算.md

動機來自實驗室的邊坡監測種子計畫:把 IMU 埋進邊坡或裝在傾斜管上,從加速度與角速度分辨土體緩慢滑動、交通或地震的振動,以及感測器本身被轉動。這必須先知道姿態(重力在機體座標系的方向),才能扣掉重力、把殘餘加速度投影到大地座標系、再積分成速度與位移;筆記裡反覆出現的「基線跟 roll、pitch、yaw 的關係?」正是這個場景的痕跡。實驗平台是 Arduino 上的 MPU-6050 與 MPU-9250(內含 AK8963 磁力計),以 VPython 可視化。一個值得記住的觀察:自己產生的假資料跑模擬輸出不正常,真實感測器資料卻正常,暗示假資料違反了單位四元數或重力一致性之類的隱含條件。The motivation is the lab's slope-monitoring seed project: bury an IMU in a slope or mount it on an inclinometer casing, and use acceleration and angular rate to separate slow sliding of the soil, vibration from traffic or earthquakes, and rotation of the sensor itself. That needs the attitude first (the direction of gravity in the body frame) so that gravity can be subtracted, the residual projected into the earth frame and integrated into velocity and displacement; the recurring question "how does the baseline relate to roll, pitch and yaw?" is the trace of this use case. The platform was an MPU-6050 and an MPU-9250 (with an AK8963 magnetometer inside) on an Arduino, visualised in VPython. One observation worth keeping: self-generated fake data gave abnormal simulation output while real sensor data worked, which suggests the fake data violated implicit constraints such as unit quaternion length or gravity consistency.動機は研究室の斜面監視シードプロジェクトだ。IMU を斜面に埋めるか傾斜計管に取り付け、加速度と角速度から土塊のゆっくりした滑動、交通や地震の振動、センサー自体の回転を区別する。そのためにはまず姿勢(機体座標系での重力方向)が要り、重力を差し引き、残留加速度を大地座標系へ投影し、速度と変位へ積分する。繰り返し現れる「ベースラインは roll・pitch・yaw とどう関係するのか?」はこの用途の痕跡だ。実験環境は Arduino 上の MPU-6050 と MPU-9250(AK8963 磁気センサー内蔵)で、VPython で可視化した。覚えておく価値のある所見が一つある。自作の擬似データではシミュレーション出力が異常になるが実センサーのデータなら正常で、擬似データが単位四元数や重力の整合性といった暗黙の制約を破っていたことを示唆する。

四元數與旋轉(四元數.md)Quaternions and rotation (四元數.md)四元数と回転(四元數.md)

來源筆記:Source notes: 出典ノート:四元數.md, 姿態估計.md

四元數.md 是連結清單加一段 Python。連結涵蓋四元數旋轉基礎(openhome.cc、meccanismocomplesso)、四元數與陀螺儀(math.stackexchange、CSDN)、重力補償(varesano.net、stackoverflow、owen-lu)。最值得保留的是 x-io 的開源 IMU/AHRS 演算法,即 Madgwick 與 Mahony 濾波器的 C 實作,後面幾篇的程式片段都源自這裡。核心公式:向量 v 繞單位軸 n 轉 θ 為 v′ = q v q-1,q = (cos(θ/2), sin(θ/2)·n);陀螺儀給機體角速度 ω,四元數變化率 q̇ = ½ q ⊗ (0, ω),積分即得姿態(姿態估計.md 又從 math.stackexchange 與 lucidar.me 的 MATLAB 範例各抄一次)。四元數.md is a link list plus one Python fragment. The links cover quaternion-rotation basics (openhome.cc, meccanismocomplesso), quaternions and gyroscopes (math.stackexchange, CSDN) and gravity compensation (varesano.net, stackoverflow, owen-lu). The one most worth keeping is the x-io open-source IMU and AHRS algorithms, the C implementation of the Madgwick and Mahony filters that the later notes' code fragments come from. The core formulas: rotating a vector v by θ about a unit axis n is v′ = q v q-1 with q = (cos(θ/2), sin(θ/2)·n); the gyro gives the body rate ω, the quaternion rate is q̇ = ½ q ⊗ (0, ω), and integrating it yields the attitude (姿態估計.md copies this again from math.stackexchange and the lucidar.me MATLAB example).四元數.md はリンク集に Python が一つ付いたもの。リンクは四元数回転の基礎(openhome.cc、meccanismocomplesso)、四元数とジャイロ(math.stackexchange、CSDN)、重力補償(varesano.net、stackoverflow、owen-lu)を扱う。最も残す価値があるのは x-io のオープンソース IMU/AHRS アルゴリズムで、Madgwick と Mahony フィルタの C 実装であり、後のノートのコード断片の出どころだ。中心の式は、ベクトル v を単位軸 n まわりに θ 回すと v′ = q v q-1、q = (cos(θ/2), sin(θ/2)·n)。ジャイロが機体角速度 ω を与え、四元数の変化率は q̇ = ½ q ⊗ (0, ω)、積分すれば姿勢になる(姿態估計.md は math.stackexchange と lucidar.me の MATLAB 例から再度写している)。

Python 片段用 pyquaternion 把一個向量繞固定軸轉過一串角度,每步印出旋轉後的向量、到原點的距離、與旋轉軸的內積,再用 matplotlib 畫 3D 圖;距離與內積必須維持常數,這是作者自己的正確性檢查。注意片段用 cos(α) 與 sin(α)·axis 建四元數而非半角,所以實際旋轉是 2α。The Python fragment uses pyquaternion to rotate one vector about a fixed axis through a list of angles, printing at each step the rotated vector, its distance from the origin and its dot product with the axis, then plotting in 3D with matplotlib. Distance and dot product must stay constant, which is the author's own correctness check. Note that the fragment builds the quaternion from cos(α) and sin(α)·axis rather than the half angle, so the rotation actually applied is 2α.Python 断片は pyquaternion で一つのベクトルを固定軸まわりに一連の角度だけ回し、各ステップで回転後のベクトル、原点からの距離、軸との内積を出力して matplotlib で 3D 描画する。距離と内積は一定でなければならず、これが著者自身の検証だ。断片は半角ではなく cos(α) と sin(α)·axis で四元数を作るので、実際の回転は 2α になる点に注意。

a = cos(angle); b, c, d = sin(angle) * axis     # full angle, so the rotation is 2*angle
q1 = Quaternion(a, b, c, d); q2 = q1.inverse
output = q1 * vector * q2                       # q v q^-1
dist = sqrt(output[1]**2 + output[2]**2 + output[3]**2)              # constant
internal = output[1]*axis[0] + output[2]*axis[1] + output[3]*axis[2] # constant

姿態估計(姿態估計.md):尤拉角、奇異點與 TKJ 的 Kalman 程式Attitude estimation (姿態估計.md): Euler angles, the singularity and the TKJ Kalman code姿勢推定(姿態估計.md):オイラー角、特異点、TKJ の Kalman コード

來源筆記:Source notes: 出典ノート:姿態估計.md, kalman filter.md

這是最長的一篇,從 1/17 的日期條目開始,收集了姿態估計流程圖(Annals of Biomedical Engineering 2017 的論文)、四元數微分、四元數與尤拉角互換(Wikipedia)、兩種等價的旋轉矩陣推導、旋轉參考座標系與科氏力的條目、一位同學推薦的 Hartley 與 Zisserman 教科書,以及 Stengel 的四元數講義。作者要的流程:先得到姿態,再用 Q-1 a Q 把三軸加速度轉到絕對座標系。This is the longest note. It opens with a dated entry (1/17) and collects an attitude-estimation flow chart (from a 2017 Annals of Biomedical Engineering paper), quaternion differentiation, the Wikipedia page on quaternion and Euler-angle conversion, two equivalent rotation-matrix derivations, the pages on rotating reference frames and the Coriolis force, the Hartley and Zisserman textbook recommended by a labmate, and Stengel's quaternion lecture notes. The pipeline the author wants: obtain the attitude, then map the measured acceleration into the absolute frame with Q-1 a Q.最長のノートだ。日付付き項目(1/17)で始まり、姿勢推定のフローチャート(Annals of Biomedical Engineering 2017 の論文)、四元数の微分、四元数とオイラー角の変換(Wikipedia)、等価な二通りの回転行列の導出、回転座標系とコリオリ力の項目、同級生が薦めた Hartley と Zisserman の教科書、Stengel の四元数講義ノートを集めている。著者の求める流れは、姿勢を得てから Q-1 a Q で測定加速度を絶対座標系へ写すこと。

尤拉角慣例。結論是 Tait-Bryan 角、內旋、順序 yaw → pitch → roll:只有 yaw 繞絕對 z 軸,pitch 與 roll 分別繞轉過之後的新 y 軸與新 x 軸,矩陣寫成 Rx·Ry·Rz·v。這是航太定義;筆記另記下知乎的內旋/外旋文章與 ctralie.com 的視覺化。NED 與 ENU 都出現在 NXP AN5017 和 TKJ 程式裡,但程式只能二選一。Euler-angle convention. The conclusion: Tait-Bryan angles, intrinsic rotation, in the order yaw, pitch, roll. Only yaw is about the absolute z axis; pitch and roll are about the new y and new x axes after the previous rotation, so the matrix is Rx·Ry·Rz·v. This is the aerospace definition; the note also records a Zhihu article on intrinsic versus extrinsic order and the ctralie.com visualiser. Both NED and ENU appear in NXP AN5017 and in the TKJ code, but a program must pick one.オイラー角の規約。結論は Tait-Bryan 角、内的回転、順序は yaw → pitch → roll。yaw だけが絶対 z 軸まわりで、pitch と roll は回転後の新しい y 軸と新しい x 軸まわりになり、行列は Rx·Ry·Rz·v。これは航空宇宙の定義で、ノートは知乎の内旋/外旋の記事と ctralie.com の可視化も記す。NED と ENU は NXP AN5017 と TKJ コードの両方に出るが、プログラムはどちらかを選ぶしかない。

pitch = ±90° 奇異點。引用 CH Robotics 的「Understanding Euler Angles」:pitch 不能踩到 ±90°,否則機體角速度到尤拉角速率的轉換矩陣會爆掉;pitch 越過 90° 時,等效描述是 yaw 轉 180°、roll 轉 −180°、pitch 拉回接近 90°,所以圖裡 yaw 與 roll 會跳到 ±180°。作者原本看不懂這張圖,後來劃掉疑問並註明:在 90° 時 roll 與 yaw 可視為不確定。The pitch = ±90° singularity. Citing CH Robotics' "Understanding Euler Angles": pitch must never reach ±90°, or the matrix from body rates to Euler rates blows up; when pitch passes 90° the equivalent description is yaw rotated 180°, roll −180° and pitch pulled back towards 90°, which is why yaw and roll jump to ±180° in the plot. The author first could not read that plot, then struck the question out and noted that at 90° roll and yaw can be treated as undefined.pitch = ±90° の特異点。CH Robotics の「Understanding Euler Angles」を引く。pitch は ±90° に達してはならず、さもないと機体角速度からオイラー角速度への行列が発散する。pitch が 90° を越えると等価な記述は yaw を 180°、roll を −180° 回して pitch を 90° 近くへ戻すものになり、だからグラフで yaw と roll が ±180° へ跳ぶ。著者は最初このグラフが読めなかったが、後に疑問を取り消し、90° では roll と yaw は不定とみなせると注記した。

重力分量與 yaw 無關。NXP AN3461 式 24:用 Rxyz 順序時,重力在機體三軸的分量只需 roll 與 pitch,作者粗體寫下「難以接受」並貼了推導。理由其實簡單:yaw 是繞重力軸本身的旋轉,不改變重力向量。同文的式 25/26 與 28/29 是「限制 pitch」與「限制 roll」兩種解,即 TKJ 程式裡 RESTRICT_PITCH 的來源。Gravity components do not depend on yaw. NXP AN3461 eq. 24: with the Rxyz order, the body-frame components of gravity need only roll and pitch. The author wrote "hard to accept" in bold and pasted the derivation. The reason is simple: yaw is a rotation about the gravity axis itself and cannot change the gravity vector. Equations 25/26 and 28/29 of the same note are the "restrict pitch" and "restrict roll" solutions, the origin of RESTRICT_PITCH in the TKJ code.重力成分は yaw に依存しない。NXP AN3461 式 24、Rxyz の順序なら機体三軸の重力成分は roll と pitch だけで決まる。著者は太字で「受け入れがたい」と書き導出を貼った。理由は単純で、yaw は重力軸そのもののまわりの回転だから重力ベクトルを変えられない。同文書の式 25/26 と 28/29 が「pitch を制限」「roll を制限」の二解で、TKJ コードの RESTRICT_PITCH の出どころだ。

機體角速度到尤拉角速率。作者問:陀螺儀 z 軸積分就是航向嗎?要不要先乘 cos(pitch)?CH Robotics 的答案:令 p、q、r 為機體 x、y、z 軸陀螺儀輸出,則Body rates to Euler rates. The author asks whether integrating the z gyro gives the heading, or whether it must be multiplied by cos(pitch) first. CH Robotics answers: with p, q, r the body x, y, z gyro outputs,機体角速度からオイラー角速度へ。著者は z ジャイロの積分が方位なのか、先に cos(pitch) を掛けるのかを問う。CH Robotics の答えは、p、q、r を機体 x、y、z 軸のジャイロ出力として、

[phi_dot  ]   [ 1   sin(phi)tan(theta)   cos(phi)tan(theta) ] [ p ]
[theta_dot] = [ 0   cos(phi)             -sin(phi)          ] [ q ]
[psi_dot  ]   [ 0   sin(phi)/cos(theta)  cos(phi)/cos(theta)] [ r ]

筆記用 Python 驗證:roll = 95.7296°(即 π/2 + 0.1 rad)、pitch = yaw = 0、機體角速度 [0, 100, 0],得慣性座標系角速率 [0, −9.983, 99.500];轉換矩陣第二、三列為 [0, −0.0998, 0.9950] 與 [0, 0.9950, −0.0998],與其反矩陣相乘確為單位矩陣;反向把絕對角速度 [0, 100, 0] 乘反矩陣,得陀螺儀應量到的 [0, 10.186, 101.524]。例子說明 roll 超過 90° 後,繞機體 y 軸的轉動幾乎全變成 yaw 速率,而 pitch 速率反號。The note checks this in Python: roll = 95.7296° (that is π/2 + 0.1 rad), pitch = yaw = 0, body rate [0, 100, 0], giving inertial-frame rates [0, −9.983, 99.500]; the second and third rows of the matrix are [0, −0.0998, 0.9950] and [0, 0.9950, −0.0998], and the product with the inverse is the identity. Going back, the absolute rate [0, 100, 0] times the inverse gives the body rate the gyro would measure, [0, 10.186, 101.524]. The example shows that once roll exceeds 90°, rotation about the body y axis becomes almost entirely yaw rate and the pitch rate changes sign.ノートはこれを Python で検証する。roll = 95.7296°(すなわち π/2 + 0.1 rad)、pitch = yaw = 0、機体角速度 [0, 100, 0] で慣性座標系の角速度は [0, −9.983, 99.500]。行列の第二・第三行は [0, −0.0998, 0.9950] と [0, 0.9950, −0.0998] で、逆行列との積は単位行列。逆に絶対角速度 [0, 100, 0] に逆行列を掛けるとジャイロが測るはずの [0, 10.186, 101.524] が出る。この例は roll が 90° を越えると機体 y 軸まわりの回転がほぼ yaw 速度になり pitch 速度の符号が反転することを示す。

TKJ 的 Kalman MPU6050 範例。兩篇筆記都以 TKJ Electronics 的 KalmanFilter(Kalman.cpp 與 examples/MPU6050/MPU6050.ino)為範本,作者記下三個怪招。一、RESTRICT_PITCH:開啟時 roll = atan2(accY, accZ)、pitch = atan(-accX / sqrt(accY² + accZ²))(式 25、26);關閉時 roll 用 atan、pitch 用 atan2(式 28、29),各把一個角限制在 ±90° 內以避開 atan2 的 ±180° 跳變。二、±180° 接縫:若 roll < -90 && kalAngleX > 90 或 roll > 90 && kalAngleX < -90,表示加速規 roll 剛跨過 ±π 而 Kalman 還落在另一側,就用 setAngle(roll) 把 Kalman、互補與純陀螺儀三個狀態一次重設。三、if (abs(kalAngleX) > 90) gyroYrate = -gyroYrate;:roll 超過 ±90° 時反轉 pitch 陀螺儀速率,才對得上被限制的加速規 pitch;作者寫了一段推理又劃掉,最後用上面的角速率矩陣說服自己。另記兩個事實:陀螺儀積分誤差太大,不單獨用來算姿態;加速規只定 roll 與 pitch,yaw 要靠磁力計,六軸只能得相對航向。The TKJ Kalman MPU6050 example. Both notes use TKJ Electronics' KalmanFilter (Kalman.cpp and examples/MPU6050/MPU6050.ino) as the template, and the author recorded three quirks. First, RESTRICT_PITCH: when defined, roll = atan2(accY, accZ) and pitch = atan(-accX / sqrt(accY² + accZ²)) (eq. 25, 26); otherwise roll uses atan and pitch atan2 (eq. 28, 29), each variant keeping one angle inside ±90° to avoid the ±180° discontinuity of atan2. Second, the ±180° seam: if roll < -90 && kalAngleX > 90 or roll > 90 && kalAngleX < -90, the accelerometer roll has just crossed ±π while the Kalman estimate is still on the other side, so setAngle(roll) resets the Kalman, complementary and pure-gyro states at once. Third, if (abs(kalAngleX) > 90) gyroYrate = -gyroYrate;: beyond ±90° of roll the pitch gyro rate is inverted to match the restricted accelerometer pitch; the author wrote a line of reasoning, struck it out, and finally convinced himself with the rate matrix above. Two further facts: gyro integration drifts too much to be used alone for attitude, and the accelerometer fixes only roll and pitch, so yaw needs a magnetometer and six axes give at best a relative heading.TKJ の Kalman MPU6050 例。両ノートとも TKJ Electronics の KalmanFilter(Kalman.cpp と examples/MPU6050/MPU6050.ino)を雛形とし、著者は三つの癖を記録した。第一に RESTRICT_PITCH。定義時は roll = atan2(accY, accZ)、pitch = atan(-accX / sqrt(accY² + accZ²))(式 25、26)、未定義時は roll が atan、pitch が atan2(式 28、29)で、どちらも一方の角を ±90° 以内に抑えて atan2 の ±180° 不連続を避ける。第二に ±180° の継ぎ目。roll < -90 && kalAngleX > 90 または roll > 90 && kalAngleX < -90 なら加速度計の roll が ±π を跨いだ直後で Kalman がまだ反対側にいるので、setAngle(roll) で Kalman、相補、純ジャイロの三状態を一度に再設定する。第三に if (abs(kalAngleX) > 90) gyroYrate = -gyroYrate;。roll が ±90° を越えたら pitch ジャイロ速度を反転させ、制限された加速度計 pitch と合わせる。著者は推論を書いて取り消し、最終的に上の角速度行列で納得した。さらに二つの事実、ジャイロ積分は誤差が大きすぎて単独では姿勢に使えないこと、加速度計は roll と pitch しか決められず yaw には磁気センサーが要り 6 軸では相対方位止まりであること。

感測器候選。筆記末尾列了候選 IC,附 ST 的 IMU 產品線圖、耗電量比較與 Analog Dialogue「如何選擇 MEMS 加速規」一文。價格是當時記下的粗略數字。Sensor shortlist. The end of the note lists candidate ICs, with ST's IMU product line, a power comparison and the Analog Dialogue article on choosing a MEMS accelerometer. Prices are the rough figures written at the time.センサー候補。ノートの末尾に候補 IC が並び、ST の IMU 製品ライン、消費電力比較、Analog Dialogue の「MEMS 加速度計の選び方」が添えられる。価格は当時の概数だ。

零件Part部品 軸數Axes軸数 等級Gradeグレード 為何考慮Why considered検討理由
MPU-6050 / MPU-92506 / 9(含 AK8963 磁力計)6 / 9 (AK8963 magnetometer inside)6 / 9(AK8963 磁気センサー内蔵)消費級consumer民生用實驗起點;TKJ 與 kriswiner 的範例都以它為對象。The starting point; the TKJ and kriswiner examples target it.実験の出発点。TKJ と kriswiner の例が対象とする。
IIS3DHHC3 軸加速規3-axis accelerometer3 軸加速度計工業級(ST)industrial (ST)産業用(ST)「不到 400 元的線性加速規」,低雜訊,適合傾斜與緩慢位移。"A linear accelerometer for under 400", low noise, suited to tilt and slow displacement.「400 元未満の線形加速度計」、低ノイズで傾斜と緩慢な変位向き。
LSM9DS19消費級(ST)consumer (ST)民生用(ST)可直接輸出線性加速度。Outputs linear acceleration directly.線形加速度を直接出力する。
ASM330LHH6車規(ST)automotive (ST)車載用(ST)筆記寫「線性加速度?」,未確認。The note says "linear acceleration?", unconfirmed.ノートには「線形加速度?」とあり未確認。
BNO0559消費級(Bosch)consumer (Bosch)民生用(Bosch)晶片內建融合,直接輸出四元數姿態,省掉自己寫 AHRS。On-chip fusion outputs the attitude as a quaternion, so no AHRS to write.オンチップ融合で姿勢を四元数として出力し、AHRS を自作しなくてよい。
ADIS164676工業級(Analog Devices)industrial (Analog Devices)産業用(Analog Devices)「可能買這台,兩萬出頭」;低偏移漂移,認真做位移積分的選擇。"May buy this one, just over twenty thousand"; low bias drift, the serious choice for displacement integration.「これを買うかも、二万元強」。バイアスドリフトが小さく、変位積分を本気でやるなら本命。

Kalman 濾波(kalman filter.md):五條公式與位移估計Kalman filtering (kalman filter.md): the five equations and displacementKalman フィルタ(kalman filter.md):五つの式と変位推定

來源筆記:Source notes: 出典ノート:kalman filter.md

kalman filter.md 是註解過的連結清單:公式推導(CSDN)、模型準與不準時結果的比較(21ic 論壇,重點是模型失配下濾波器仍收斂)、MATLAB 程式與參數說明、kalmanfilter.net 的一維教學、ilectureonline 的線上課程。作者註記「五條公式要熟記」,即標準的預測/更新:kalman filter.md is an annotated link list: a derivation (CSDN), a comparison of results with an accurate and an inaccurate model (a 21ic forum thread; the point is that the filter still converges under model mismatch), MATLAB code with parameter notes, the one-dimensional tutorial on kalmanfilter.net, and the ilectureonline video course. The author writes "the five equations, memorise them", meaning the standard predict and update steps:kalman filter.md は注釈付きリンク集だ。式の導出(CSDN)、モデルが正確な場合と不正確な場合の結果比較(21ic フォーラム、要点はモデル不一致でも収束すること)、パラメータ説明付き MATLAB コード、kalmanfilter.net の一次元チュートリアル、ilectureonline の動画講義。著者は「五つの式を暗記せよ」と書き、標準の予測・更新を指す。

predict:  x_pred = A x + B u
          P_pred = A P A' + Q
update:   K      = P_pred H' (H P_pred H' + R)^-1
          x      = x_pred + K (z - H x_pred)
          P      = (I - K H) P_pred

筆記引用一篇 MPU-6050 部落格:加速規長期穩定但短期可能劇烈振盪,陀螺儀短期可靠但長期漂移,Kalman 與互補濾波都是結合兩者。TKJ 的「A practical approach to Kalman filter」與 Kalman.cpp 是選定的實作範本。兩則日期條目把題目轉向位移。1/16:指導老師找到以定點數實作 Kalman 的開源碼(GitHub kalman-filter 主題、C 語言),對沒有浮點的 MCU 很重要;同日記下「用 Kalman 估計位移?」,連到 Akron 大學的碩士論文與 dsp.stackexchange 上位置與速度 Kalman 的問答。1/27:補一篇作者認為「寫得很好」的 Acta Mechanica et Automatica 論文(第 8 卷第 2 期第 88 頁),同時估計位移、速度與加速度誤差,貼了四張狀態方程式截圖。The note quotes an MPU-6050 blog: the accelerometer is stable in the long run but can oscillate violently in the short run, the gyro is reliable in the short run but drifts, and Kalman and complementary filters both combine the two. TKJ's "A practical approach to Kalman filter" and its Kalman.cpp are the chosen implementation template. Two dated entries turn to displacement. 1/16: the advisor found an open-source fixed-point Kalman implementation (GitHub kalman-filter topic, in C), which matters for an MCU without floating point; the same day records "use Kalman to estimate displacement?" with links to a University of Akron master's thesis and the dsp.stackexchange question on a position-and-velocity Kalman filter. 1/27: a paper from Acta Mechanica et Automatica (vol. 8 no. 2, p. 88) that the author calls "very well written", estimating displacement, velocity and acceleration error together, with four screenshots of its state equations.ノートは MPU-6050 のブログを引く。加速度計は長期的には安定だが短期的には激しく振動しうる、ジャイロは短期的には信頼できるが長期的にドリフトする、Kalman も相補フィルタも両者を組み合わせる。TKJ の「A practical approach to Kalman filter」と Kalman.cpp が選ばれた実装の雛形だ。二つの日付付き項目が変位へ向かう。1/16、指導教員が固定小数点で Kalman を実装したオープンソース(GitHub kalman-filter トピック、C 言語)を見つけた。浮動小数点のない MCU には重要だ。同日「Kalman で変位を推定?」と書き、Akron 大学の修士論文と dsp.stackexchange の位置と速度の Kalman フィルタの質問をリンクした。1/27、著者が「とてもよく書けている」と評する Acta Mechanica et Automatica の論文(第 8 巻第 2 号 88 頁)を追加。変位、速度、加速度誤差を同時に推定するもので、状態方程式のスクリーンショットが四枚ある。

要點:加速規長期準、短期吵;陀螺儀短期準、長期漂。Kalman 與互補濾波都只是按可信度加權兩者,差別在權重是固定(互補)還是由共變異數自動調整(Kalman)。Takeaway: the accelerometer is right on average but noisy moment to moment; the gyro is right moment to moment but drifts. Kalman and complementary filters both weight the two by trust; the difference is whether the weight is fixed (complementary) or adapted by the covariance (Kalman).要点:加速度計は平均では正しいが瞬間的にはうるさく、ジャイロは瞬間的には正しいがドリフトする。Kalman も相補フィルタも両者を信頼度で重み付けするだけで、違いは重みが固定(相補)か共分散で自動調整される(Kalman)かだ。

AHRS(ahrs.md):Mahony 濾波器、磁力計與線性加速度AHRS (ahrs.md): the Mahony filter, the magnetometer and linear accelerationAHRS(ahrs.md):Mahony フィルタ、磁気センサー、線形加速度

來源筆記:Source notes: 出典ノート:ahrs.md, 姿態估計.md

ahrs.md 以「校正軌跡的方式?」開頭,接著是一篇 itread01 姿態文章與一篇 CSDN 的 Mahony 文章。Mahony 濾波器:用目前的四元數算出重力在機體座標系的預期方向,與正規化後的加速規向量做外積得誤差 e,經 PI 控制器(Kp·e + Ki·∫e)修正陀螺儀讀值,再積分四元數。姿態估計.md 留了「PI 消除誤差,不太懂什麼誤差」:答案是陀螺儀偏移,積分項就是在線估計它;ahrs.readthedocs.io 的 Mahony 頁是正式推導。作者並排比較尤拉角與四元數推出的旋轉矩陣:第三欄略有差異,歸因於旋轉順序;右下角元素是兩個平方項之和,單位四元數可化簡但有些程式仍照原式算;x-IMU 程式裡的正負號差異也歸於旋轉順序。另一個陷阱來自 endaq 部落格:同一姿態可由 q 或 −q 表示。筆記還有單軸旋轉的截圖與一位同學丟到群組的流程圖。ahrs.md opens with "how to correct the trajectory?", then an itread01 attitude article and a CSDN article on Mahony. The Mahony filter: from the current quaternion compute the expected direction of gravity in the body frame, cross it with the normalised accelerometer vector to get an error e, pass it through a PI controller (Kp·e + Ki·∫e) to correct the gyro reading, then integrate the quaternion. 姿態估計.md keeps "PI removes an error, not sure which": the answer is the gyro bias, which the integral term estimates online; the Mahony page on ahrs.readthedocs.io is the formal derivation. The author compared the Euler-angle and quaternion rotation matrices side by side: the third column differs slightly, attributed to rotation order; the bottom-right element is a sum of two squares that simplifies for a unit quaternion, though some code evaluates the full form; sign differences in the x-IMU code are also put down to rotation order. Another trap, from the endaq blog: the same attitude is represented by both q and −q. The note also keeps screenshots of single-axis rotations and a flow chart a labmate posted in the group chat.ahrs.md は「軌跡を補正する方法は?」で始まり、itread01 の姿勢記事と CSDN の Mahony 記事が続く。Mahony フィルタは、現在の四元数から機体座標系での重力の予想方向を計算し、正規化した加速度計ベクトルとの外積で誤差 e を得て、PI 制御器(Kp·e + Ki·∫e)でジャイロ読み値を補正し、四元数を積分する。姿態估計.md には「PI で誤差を消すとあるが何の誤差か」が残る。答えはジャイロのバイアスで、積分項がオンラインで推定する。ahrs.readthedocs.io の Mahony ページが正式な導出だ。著者はオイラー角と四元数から導いた回転行列を並べて比較した。第三列がわずかに異なり回転順序の差に帰す。右下の要素は二つの平方の和で単位四元数なら簡約できるが一部のコードは元の式のまま計算する。x-IMU コードの符号の違いも回転順序に帰す。もう一つの罠は endaq ブログから、同じ姿勢は q でも −q でも表せる。ノートには単軸回転のスクリーンショットと、同級生がグループチャットに投げたフローチャートもある。

線性加速度。兩步:一、用最新的 q 算出重力方向 v,從加速規讀值減掉,x-IMU 程式的三行就是 v 的一半。二、把機體座標系的線性加速度轉到大地座標系,筆記寫 q.inverse * a * q <-- ??:該用 q a q-1 還是 q-1 a q,取決於 q 定義的是機體到大地還是大地到機體,各程式庫慣例不同。Linear acceleration. Two steps: first, compute the gravity direction v from the latest q and subtract it from the accelerometer reading; three lines of the x-IMU code give half of v. Second, rotate the body-frame linear acceleration into the earth frame; the note writes q.inverse * a * q <-- ??, since whether it is q a q-1 or q-1 a q depends on whether q is body-to-earth or earth-to-body, and libraries differ.線形加速度。二段階で、第一に最新の q から重力方向 v を計算して加速度計の読み値から引く。x-IMU コードの三行が v の半分を与える。第二に機体座標系の線形加速度を大地座標系へ回す。ノートには q.inverse * a * q <-- ?? とあり、q a q-1 か q-1 a q かは q が機体から大地か大地から機体かの定義に依存し、ライブラリごとに異なる。

// Estimated direction of gravity (half of the unit vector), body frame
halfvx = q1 * q3 - q0 * q2;
halfvy = q0 * q1 + q2 * q3;
halfvz = q0 * q0 - 0.5f + q3 * q3;

磁力計。這部分收集 CSDN 與知乎的文章(其中一篇題為「磁力計效果不大?」),以及橢圓擬合校正的參考(Fierce Electronics 的傾斜、硬鐵與軟鐵補償、VectorNav 的磁力計校正頁)。核心概念:機體座標系量到的磁場向量先轉到地理座標系、處理後再轉回來,得到理論地磁向量;本質是校正四元數,讓反轉換後的 x 軸對準正北。作者在一張公式截圖旁註「右邊有問題,中間不該為 0」,指參考磁場的東向分量。實作範本是 kriswiner MPU9250 AHRS 程式的 magcalMPU9250():提示畫 8 字形,延遲 4 秒後蒐集約 15 秒樣本(8 Hz 模式 128 筆、間隔 135 ms;100 Hz 模式 1500 筆、間隔 12 ms),逐軸記錄最大最小值;硬鐵偏移 = (max + min)/2,乘 mRes 與出廠靈敏度係數換算成高斯;軟鐵估計取各軸半弦長 (max − min)/2 的平均 avg_rad,各軸縮放係數 = avg_rad / 該軸半弦長。這是軸對齊的簡化近似,不是完整橢球擬合。作者留了兩個問題:「軟鐵估計之後在寫什麼?」(答:dest2 是各軸縮放係數,主程式扣掉偏移後逐軸相乘);initAK8963(magCalibration) 讀的「9250 內部 ROM 參數」是什麼(答:AK8963 的出廠靈敏度調整值 ASA,每軸一個)。筆記末尾的雜記:一位同學做了新版板子;VPython 建 canvas 時加 scene.forward = vec(-1, 0, 0)、scene.up = vec(0, 0, 1)、scene.camera.pos = vec(-1, 0, 0) 讓 z 軸朝上;Eagle PCB 在 Linux 上免費。Magnetometer. This part collects CSDN and Zhihu articles (one titled "is the magnetometer of little use?") and ellipsoid-fitting references (Fierce Electronics on tilt, hard-iron and soft-iron compensation, the VectorNav magnetometer calibration page). The core idea: rotate the body-frame magnetic vector into the geographic frame, process it, and rotate it back to obtain the theoretical geomagnetic vector; in essence, calibrate the quaternion so that the inverse-rotated x axis points to true north. Next to one formula the author wrote "the right-hand side is wrong, the middle term should not be 0", meaning the east component of the reference field. The implementation template is magcalMPU9250() from kriswiner's MPU9250 AHRS sketch: prompt a figure eight, wait 4 s, collect about 15 s of samples (128 samples 135 ms apart in the 8 Hz mode, 1500 samples 12 ms apart at 100 Hz), tracking per-axis max and min; hard-iron bias = (max + min)/2, converted to gauss through mRes and the factory sensitivity factor; the soft-iron estimate averages the per-axis half chords (max − min)/2 into avg_rad and scales each axis by avg_rad divided by its own half chord. This is the axis-aligned approximation, not a full ellipsoid fit. The author left two questions: "what does the part after the soft-iron estimate do?" (answer: dest2 holds per-axis scale factors that the main program multiplies in after subtracting the bias), and what the "9250 internal ROM parameters" read by initAK8963(magCalibration) are (answer: the AK8963 factory sensitivity adjustment values, ASA, one per axis). Stray lines at the end: a labmate built a new board revision; when creating the VPython canvas add scene.forward = vec(-1, 0, 0), scene.up = vec(0, 0, 1) and scene.camera.pos = vec(-1, 0, 0) so that z points up; Eagle PCB is free on Linux.磁気センサー。この部分は CSDN と知乎の記事(うち一つは「磁気センサーは効果が薄い?」)と楕円体フィッティングの参照(Fierce Electronics の傾斜・ハードアイアン・ソフトアイアン補償、VectorNav の磁気センサー校正ページ)を集める。核心の考えは、機体座標系で測った磁気ベクトルを地理座標系へ回し、処理してから戻すと理論地磁気ベクトルが得られること。要は四元数を校正して逆変換後の x 軸を真北に向ける。ある式の横に著者は「右辺がおかしい、中央は 0 であってはならない」と書き、参照磁場の東成分を指す。実装の雛形は kriswiner の MPU9250 AHRS スケッチの magcalMPU9250()。8 の字に振るよう促し、4 秒待って約 15 秒分のサンプルを集め(8 Hz モードで 135 ms 間隔 128 個、100 Hz で 12 ms 間隔 1500 個)、軸ごとに最大最小を追跡する。ハードアイアンのバイアス = (max + min)/2 を mRes と工場出荷時感度係数でガウスに換算し、ソフトアイアンの推定は軸ごとの半弦長 (max − min)/2 の平均 avg_rad を取り、各軸を avg_rad をその軸の半弦長で割った係数で拡大縮小する。これは軸に揃った簡易近似で、完全な楕円体フィッティングではない。著者は二つの疑問を残した。「ソフトアイアン推定の後は何をしているのか」(答え:dest2 は軸ごとの係数で、メインがバイアスを引いた後に掛ける)、initAK8963(magCalibration) が読む「9250 内部 ROM のパラメータ」とは何か(答え:AK8963 の工場出荷時感度調整値 ASA、軸ごとに一つ)。末尾の雑記として、同級生が新版の基板を作ったこと、VPython の canvas 作成時に scene.forward = vec(-1, 0, 0)、scene.up = vec(0, 0, 1)、scene.camera.pos = vec(-1, 0, 0) を加えて z 軸を上にすること、Eagle PCB が Linux で無料なこと。

位移計算(位移計算.md):ZVU、反向積分與漂移移除Displacement (位移計算.md): ZVU, backward integration and drift removal変位計算(位移計算.md):ZVU、逆方向積分、ドリフト除去

來源筆記:Source notes: 出典ノート:位移計算.md, 姿態估計.md

位移計算.md 的骨幹是 ST 的設計提示「以重力扣除求殘餘線性加速度以實現航位推算」。流程已寫在 姿態估計.md:知道姿態後,把相對加速度轉成絕對加速度,積分兩次,每次積分前先高通濾波;x-io 的「Oscillatory Motion Tracking With x-IMU」是公開示範。ST 文件被整段抄下的技巧是零速度更新(ZVU):加速度模長為 1 g 且陀螺儀接近 0 時,假設速度為零並重設積分器(velhp(i,:) = [0,0,0])。文件自己點出失效模式:等速運動會誤觸發重設,所以應用場景必須是等速不太可能發生的情況。若不要求即時,可從目前 ZVU 點往前一個 ZVU 點反向積分,權重 W 從 1 線性降到 0,與權重 1 − W 的正向積分器混合,抹平重設瞬間的跳變。作者粗體加上自己的觀察:走路這種振動 pattern 不適合 ZVU,因為波峰與波谷時加速度為 0 但速度不為 0,ZVU 卻會強制歸零;邊坡上車輛經過的振動同樣會讓 ZVU 誤判。位移計算.md is built around ST's design tip on residual linear acceleration by gravity subtraction for dead reckoning. The pipeline is already in 姿態估計.md: once the attitude is known, convert relative to absolute acceleration and integrate twice, high-pass filtering before each integration; x-io's "Oscillatory Motion Tracking With x-IMU" is the public demonstration. The technique copied verbatim from ST is the Zero-Velocity Update (ZVU): when the modulus of the acceleration is 1 g and the gyro output is near 0, the velocity is assumed zero and the integrator reset (velhp(i,:) = [0,0,0]). The document names its own failure mode: a constant velocity would falsely trigger the reset, so the application must be one where constant velocity is unlikely or impossible. Without a real-time requirement, one can integrate backward from the current ZVU point to the previous one with a weight W falling linearly from 1 to 0, mixed with the forward integrator weighted 1 − W, to smooth the jump at the reset. The author adds his own observation in bold: a walking-type vibration pattern does not suit ZVU, because at the peaks and troughs the acceleration is 0 while the velocity is not, yet ZVU forces it to zero; vibration from vehicles passing a slope would fool ZVU the same way.位移計算.md の骨格は ST のデザインチップ「重力差し引きによる残留線形加速度で推測航法を可能にする」だ。流れは 姿態估計.md にすでにある。姿勢がわかったら相対加速度を絶対加速度に変換して二回積分し、各積分の前にハイパスフィルタをかける。x-io の「Oscillatory Motion Tracking With x-IMU」が公開デモだ。ST から丸ごと写された技法が零速度更新(ZVU)で、加速度のノルムが 1 g でジャイロ出力がほぼ 0 なら速度を零とみなし積分器を再設定する(velhp(i,:) = [0,0,0])。文書自身が失敗モードを挙げる。等速運動は誤って再設定を引き起こすので、等速がまず起きない用途でなければならない。リアルタイムが不要なら現在の ZVU 点から前の ZVU 点へ逆方向に積分し、重み W を 1 から 0 へ線形に下げて重み 1 − W の順方向積分器と混ぜ、再設定時の跳びを滑らかにできる。著者は太字で自分の観察を加える。歩行のような振動パターンは ZVU に向かない。山と谷では加速度が 0 でも速度は 0 ではないのに ZVU は強制的に零にする。斜面を通過する車両の振動も同じように ZVU を誤らせる。

第二段程式來自 x-io 的步態追蹤範例(MATLAB),做靜止段之間的漂移移除:用 diff(stationary) 找靜止旗標的下降沿(運動開始)與上升沿(運動結束),每段的 driftRate = 到達下一個靜止點時的速度 / 該段樣本數,再把線性增長的漂移 enum' * driftRate 從速度中扣掉。筆記還抄了一段論壇經驗談:靠加速規積分做位置,AHRS 不現實,1 分鐘就飄出幾十公尺,誤差以二次方遞增;AHRS 通常要結合 GPS 與氣壓計。真能用 IMU 積分定位的是慣導等級設備,規格以「一天幾海里」計。這是 AHRS 與 INS 的差異,也是 ADIS16467 後來進入候選清單的原因。The second fragment is from x-io's gait-tracking example (MATLAB) and removes drift between stationary periods: diff(stationary) finds the falling edge (motion starts) and rising edge (motion ends) of the stationary flag, each segment's driftRate = velocity at the next stationary point / number of samples in the segment, and the linearly growing drift enum' * driftRate is subtracted from the velocity. The note also copies forum experience: for position from accelerometer integration an AHRS is unrealistic, drifting tens of metres within a minute with the error growing quadratically; an AHRS is normally fused with GPS and a barometer. Units that can genuinely integrate position are navigation grade, specified in nautical miles per day. That is the difference between an AHRS and an INS, and why the ADIS16467 later joined the shortlist.第二の断片は x-io の歩行追跡例(MATLAB)で、静止区間の間のドリフトを除去する。diff(stationary) で静止フラグの立ち下がり(運動開始)と立ち上がり(運動終了)を見つけ、各区間の driftRate = 次の静止点での速度 / 区間のサンプル数とし、線形に増えるドリフト enum' * driftRate を速度から引く。ノートはフォーラムの経験談も写す。加速度計の積分で位置を出すのに AHRS は非現実的で、1 分で数十メートルずれ誤差は二次関数的に増える。AHRS は通常 GPS と気圧計と組み合わせる。IMU の積分で本当に位置が出せるのは航法グレードで、仕様は「一日に何海里」で語られる。これが AHRS と INS の違いで、ADIS16467 が後に候補に入った理由だ。

要點:ZVU 在 |a| ≈ 1 g 且陀螺儀 ≈ 0 時把速度歸零;等速運動與振動(a = 0 但 v ≠ 0)都會讓它誤判。消費級 IMU 單靠積分做位移,一分鐘內就漂幾十公尺,誤差隨時間二次方成長。Takeaway: ZVU resets velocity when |a| ≈ 1 g and the gyro ≈ 0; constant velocity and vibration (a = 0 but v ≠ 0) both fool it. A consumer IMU integrated on its own drifts tens of metres within a minute, with the error growing quadratically in time.要点:ZVU は |a| ≈ 1 g かつジャイロ ≈ 0 のとき速度を零にする。等速運動と振動(a = 0 だが v ≠ 0)はどちらも誤作動させる。民生用 IMU を単独で積分すると一分以内に数十メートルずれ、誤差は時間の二乗で増える。

作者留下的未解問題Open questions the author left著者が残した未解決の問い

來源筆記:Source notes: 出典ノート:ahrs.md, 四元數.md, kalman filter.md, 姿態估計.md, 位移計算.md

  • 把 atan2 映射到 0~360°((x > 0 ? x : 2π + x) · 360/2π)之後,磁力計航向若突然變化約 180°,是否該判定為 pitch 的轉折點?After mapping atan2 to 0 to 360° with (x > 0 ? x : 2π + x) · 360/2π, should a sudden change of about 180° in the magnetometer heading be taken as a pitch turning point?atan2 を (x > 0 ? x : 2π + x) · 360/2π で 0〜360° に写した後、磁気センサーの方位が突然約 180° 変化したら pitch の折り返し点と判定すべきか?
  • |roll| > 90° 時,yaw rate 是否也要像 TKJ 程式對 pitch rate 那樣反號?roll 的 atan2 值加減 180° 時要怎麼映射?When |roll| > 90°, should the yaw rate be inverted the way the TKJ code inverts the pitch rate? How should the roll atan2 value be mapped when it wraps by ±180°?|roll| > 90° のとき、TKJ コードが pitch 速度を反転させるように yaw 速度も反転させるべきか?roll の atan2 値が ±180° で折り返すときはどう写すのか?
  • 大地座標系線性加速度該用 q a q-1 還是 q-1 a q?varesano.net 用四元數扣除重力的方法「不知道是否正確」。Should the earth-frame linear acceleration be q a q-1 or q-1 a q? Is the varesano.net quaternion gravity-subtraction method correct at all ("not sure if it is right")?大地座標系の線形加速度は q a q-1 か q-1 a q か?varesano.net の四元数による重力差し引きはそもそも正しいのか(「正しいかわからない」)?
  • 「基線跟 roll、pitch、yaw 的關係?」:邊坡監測的靜止基線該如何從姿態定義。AHRS 的「校正軌跡」要怎麼做?"How does the baseline relate to roll, pitch and yaw?": how the resting baseline for slope monitoring should be defined from the attitude. And how is the AHRS trajectory to be corrected?「ベースラインは roll、pitch、yaw とどう関係するのか?」:斜面監視の静止ベースラインを姿勢からどう定義するか。AHRS の「軌跡補正」はどうやるのか?
  • ZVU 在振動與等速時失效後,邊坡場景該用什麼替代判準?同時估計位移、速度與加速度誤差的 Kalman 模型能否跑在定點數 MCU 上?Once ZVU fails under vibration and constant velocity, what criterion replaces it in the slope case? Can the Kalman model that estimates displacement, velocity and acceleration error together run on a fixed-point MCU?振動と等速で ZVU が破綻した後、斜面の場面ではどんな判定基準で置き換えるのか?変位、速度、加速度誤差を同時に推定する Kalman モデルは固定小数点の MCU で動くのか?
回到頂端 ↑Back to top ↑ページ上部へ ↑

邊坡種子:埋在山坡裡的低功耗 IMU 節點(2020/11 – 2021/10 會議記錄)Slope seed: low-power IMU nodes buried in a hillside (meeting log, Nov 2020 to Oct 2021)斜面シード:山腹に埋める低消費電力 IMU ノード(2020年11月〜2021年10月の会議記録)

〈邊坡種子.md〉是 42 KB 的會議流水帳(2020/11/20 至 2021/10/4),記錄一個政府災害防救計畫的第一年與第二年初。構想是把低功耗 IMU「種子」埋進台 20 線 52K(一處隧道工區)的坡面,偵測滑動並即時告警,上有雲端儀表板,交管系負責緊急車輛派遣。內容是會後隨手記的待辦、數據與疑問(滿是「??」),本節依主題整理。極短的〈lora.md〉併入無線電小節。邊坡種子.md is a 42 KB running meeting log (20 Nov 2020 to 4 Oct 2021) of year one and early year two of a government disaster-prevention grant. The idea: bury low-power IMU "seed" nodes in the slope at Provincial Highway 20, 52K, a tunnel work site, detect sliding and alarm at once, with a cloud dashboard on top and a transportation-management department running emergency-vehicle dispatch. The note holds to-do items, measured numbers and doubts (full of "??") jotted after each meeting; this section groups them by theme. The tiny lora.md is folded into the radio subsection.「邊坡種子.md」は政府の防災助成の 1 年目と 2 年目初めを記録した 42 KB の会議ログ(2020年11月20日〜2021年10月4日)。構想は、省道 20 号線 52K(トンネル工事現場)の斜面に低消費電力の IMU「シード」ノードを埋めて滑動を検知し即座に警報を出すこと。上にクラウドのダッシュボードがあり、交通管理学科が緊急車両派遣を担う。内容は会議後に書き留めた ToDo、測定値、疑問(「??」だらけ)で、本節はテーマ別に整理する。ごく短い「lora.md」は無線の小節に組み込む。

計畫框架:目標、夥伴、三年規劃與經費規則Project framing: goals, partners, the three-year plan and budget rulesプロジェクトの枠組み:目標、パートナー、3か年計画、予算ルール

來源筆記:Source notes: 出典ノート:邊坡種子.md

三位教授共同主持:指導教授負責種子硬體與演算法,一位負責雲端與布設,一位(交管系)負責車輛派遣與對外報告。合作對象有土木系(振動平台)、測量系(GPS 與 IMU)、一家 Z-Wave 模組廠商、多家 LoRa 廠商,以及公路總局第五區養護工程處;首次場勘在 2020/12/18。三年規劃 12/15 定案:第一年做車輛派遣頁面供資料過濾;第二年改 OBU 並加「智慧貓眼」;第三年做 Android 車機,App 處理門禁、車位與調撥車道。疏散運具只用緊急車輛。Three professors run the grant: the advisor owns seed hardware and algorithm, a second the cloud side and deployment, a third (transportation management) vehicle dispatch and outward reports. Partners: the civil-engineering department (shake table), the surveying department (GPS and IMU), a Z-Wave module vendor, several LoRa vendors and the Highway Bureau's 5th maintenance office; the first site survey was on 18 Dec 2020. The three-year plan, fixed on 15 Dec: year 1 a vehicle-dispatch page for filtering data; year 2 modify the OBU and add a "smart cat-eye" road stud; year 3 an Android head unit whose app handles gate access, parking and contra-flow lanes. Evacuation covers emergency vehicles only.3 人の教授が共同運営する。指導教授がシードのハードウェアとアルゴリズム、2 人目がクラウド側と設置、3 人目(交通管理学科)が車両派遣と対外報告。協力先は土木学科(振動台)、測量学科(GPS と IMU)、Z-Wave モジュールベンダー、複数の LoRa ベンダー、公路総局第五区養護工程処で、最初の現地調査は 2020年12月18日。3か年計画は 12月15日に確定:1 年目はデータを絞り込む車両派遣ページ、2 年目は OBU 改修と「スマートキャッツアイ」追加、3 年目はゲート・駐車・リバーシブルレーンをアプリで扱う Android 車載器。避難輸送は緊急車両のみ。

經費規則:第二年有約 60 萬元量產經費與約 10 萬元專利申請(判斷滑動或地震)。2/23 準備期中報告時記下:人事費被砍到 60 萬要爭取回 140 萬、施工費一次 10 到 15 萬、兩個場地各兩個 gateway 為期一年半、每項變更只能寫一千字、小規模量產歸耗材附報價單。6/11 的會計規則:耗材單項與單張發票都不能超過一萬元,否則視為設備要貼財產標籤;土木系試驗費算業務費但計畫書未列。Budget rules: year 2 carries about NT$600k for mass production and about NT$100k for a patent (sliding versus earthquake). Preparing the mid-term report on 23 Feb: personnel cut to 600k, to be argued back to 1.4M; construction NT$100k to 150k per round; two sites with two gateways each for 18 months; a thousand characters per budget change; small-batch production booked as consumables with quotations. The 11 Jun accounting rules: a consumable item and a single invoice must each stay under NT$10k or the item becomes equipment with an asset tag; civil-engineering tests count as operating expense but were missing from the proposal.予算ルール:2 年目には約 60 万台湾ドルの量産予算と約 10 万ドルの特許出願(滑動と地震の判別)。2月23日の中間報告準備で記録:人件費は 60 万に削られ 140 万へ戻す主張、工事費は 1 回 10〜15 万、2 現場にゲートウェイ各 2 台を 18 か月、予算変更は各 1000 字、小ロット生産は見積書付きで消耗品。6月11日の会計ルール:消耗品は単品も請求書 1 枚も 1 万ドル未満、超えると設備扱いで資産ラベル。土木学科の試験は業務費だが提案書に無かった。

第一年結餘 179,583 元(收入餘額 384,864 減管理費 205,281)進校方結餘款,不能流入第二年;第二年核定額低於申請額,設備費約可留八十幾萬,雲端伺服器用現有 PC、App 交給交管系專題生。The first-year leftover of NT$179,583 (income balance 384,864 minus 205,281 overhead) goes to the university's surplus and cannot roll into year 2. Year 2 was approved below the request; about NT$800k stays for equipment, with the cloud server on an existing PC and the app given to transportation-department project students.1 年目の残額 179,583 ドル(収入残高 384,864 から間接費 205,281 を引いた額)は大学の剰余金に入り 2 年目へ繰り越せない。2 年目の承認額は申請額を下回り、設備費は約 80 万ドル強、クラウドサーバーは既存 PC、アプリは交通管理学科のプロジェクト生に任せる。

硬體:電池、省電 MCU、IMU 選型與開發環境Hardware: battery, low-power MCU, IMU choices and the toolchainハードウェア:電池、低消費電力 MCU、IMU の選定、ツールチェーン

來源筆記:Source notes: 出典ノート:邊坡種子.md

12/1 參訪 Z-Wave 廠商後記下其方案:CR123A 3 V 電池、非常省電的 g-sensor(筆記寫 lis21wd2,應是 ST LIS2DW12)與一顆「run time 耗電等於 STM32 sleep time」的 PIC。12/6 同學轉來內建 LoRa 的 STM32WLE5(active 3.456 mA)與該 PIC 的 datasheet;作者算出 PIC 主動電流 48 µA × 32 ÷ 1000 = 1.536 mA,待辦是用 g-sensor 的 INT1/INT2 喚醒 STM32。12/11 整理 STM32 低功耗層級:sleep(週邊可選)、stop(週邊關但可留一個 timer 給 sensor 時脈)、standby;感測器自身可 sleep,喚醒 1.4 ms。12/25 報告 RTC 與外部中斷兩種 stop mode 喚醒都完成,但三用電錶串聯會讓 MCU 一直 reset 而量不到電流,擬改買勾表。告警策略 1/18 定為不要死循環,除非災害嚴重。After the 1 Dec vendor visit the author recorded their design: a CR123A 3 V cell, a very low-power g-sensor (written "lis21wd2", most likely ST's LIS2DW12) and a PIC whose running current "equals an STM32's sleep current". On 6 Dec a labmate forwarded datasheets for the STM32WLE5 with built-in LoRa (3.456 mA active) and the PIC; the author worked out the PIC active current as 48 µA × 32 / 1000 = 1.536 mA, and the to-do was to wake the STM32 from the g-sensor's INT1/INT2 pins. The 11 Dec meeting sorted the STM32 low-power tiers: sleep (peripherals optional), stop (peripherals off, one timer may keep clocking the sensor) and standby; the sensor itself sleeps too, waking in 1.4 ms. On 25 Dec wake-up from stop mode by RTC and by external interrupt both worked, but a multimeter in series kept resetting the MCU, so a clamp meter was proposed. The alarm policy, fixed on 18 Jan: no endless loop unless the disaster is severe.12月1日のベンダー訪問後に記録した設計:CR123A 3 V 電池、超低消費電力の g センサー(「lis21wd2」、おそらく ST の LIS2DW12)、動作電流が「STM32 のスリープ電流に等しい」PIC。12月6日に仲間が LoRa 内蔵 STM32WLE5(アクティブ 3.456 mA)と PIC のデータシートを転送し、著者は PIC のアクティブ電流を 48 µA × 32 / 1000 = 1.536 mA と計算、ToDo は g センサーの INT1/INT2 で STM32 を起こすこと。12月11日に STM32 の低消費電力階層を整理:sleep(周辺は任意)、stop(周辺停止、タイマー 1 本でセンサーにクロック供給可)、standby。センサー自体も 1.4 ms で起床できる。12月25日、RTC と外部割り込みの両方で stop からの起床が動いたが、テスターを直列にすると MCU がリセットを繰り返して測れず、クランプメーターを検討。警報方針は 1月18日に、重大災害以外は無限ループにしないと決定。

IMU 一路升級:11/26 選 MPU-6050,1/15 I2C 讀取完成;1/22 討論升級 MPU-9250 取得磁力計校正 yaw;2/19 買防水溫濕度計與 MPU-9250 共用 I2C 匯流排(8/6 又想用它降低 false alarm);3/26 考慮 Analog Devices 加速規;4/9 發現 Bosch BNO055「把我們的 work 都做好了」,4/23 到貨三顆,先測其線性加速度能否積分,再把其感測器接自家演算法以區分問題來自感測器或演算法。同時提議買導航級 IMU 當 golden model,既知極限也能量化 cost-down 的代價;x-io 的 NGIMU 約 180 歐元但已不開源。機構上種子要固定在土木系 1 g 加速平台,治具 12/25 送加工,6/11 設計可洩土的閘門壓克力平台,3/26 採購 housing 以便全埋。10/4 採購清單:PCB 100 片、種子 50 顆、土壤溼度計 30 顆、一個場域。The IMU kept moving up: MPU-6050 chosen 26 Nov, I2C reading done 15 Jan; 22 Jan debate on the MPU-9250 for a magnetometer to correct yaw; 19 Feb a waterproof temperature/humidity sensor sharing the I2C bus with the MPU-9250 (revisited 6 Aug to cut false alarms); 26 Mar an Analog Devices accelerometer considered; 9 Apr the Bosch BNO055 found to "do everything we are doing", three arriving by 23 Apr, with the plan to test whether its linear acceleration integrates usably and then run its sensors through the lab's algorithm to attribute any gain to sensor or algorithm. A navigation-grade IMU was proposed as a golden model to learn the limit and price the cost-down; x-io's NGIMU is about 180 euro but no longer open source. Mechanically the seed is clamped to the civil-engineering 1 g shake table; the fixture went to the shop 25 Dec, an acrylic platform with a sluice gate to drain soil was designed 11 Jun, and a housing for full burial was bought 26 Mar. The 4 Oct purchase list: 100 PCBs, 50 seeds, 30 soil-moisture probes, one site.IMU は段階的に上がった。11月26日に MPU-6050、1月15日に I2C 読み出し完了。1月22日、yaw 補正用磁力計のため MPU-9250 を議論。2月19日、防水温湿度センサーを MPU-9250 と I2C バス共有で購入(8月6日に誤警報低減にも検討)。3月26日に Analog Devices の加速度計を検討。4月9日に Bosch BNO055 が「自分たちのやっていることを全部やっている」と判明し 4月23日に 3 個到着、まず線形加速度が積分に耐えるか試し、次にそのセンサーを自前アルゴリズムに通して改善がセンサー由来かアルゴリズム由来かを切り分ける。航法グレード IMU をゴールデンモデルとして買い、限界とコストダウンの代償を測る案も出た。x-io の NGIMU は約 180 ユーロだがもう非公開。機構面ではシードを土木学科の 1 g 振動台に固定し、治具は 12月25日に加工へ、6月11日に土を排出できる水門付きアクリル台を設計、完全埋設用ハウジングは 3月26日に購入。10月4日の購入リスト:PCB 100 枚、シード 50 個、土壌水分計 30 個、現場 1 か所。

工具鏈的坑:除錯設定要把 hardware reset 改成 software system reset,Linux 上要把 libncurses.so.5 連結成 libncurses.so.6。燒錄用 st-flash:Toolchain pitfalls: the debug configuration had to switch from hardware reset to software system reset, and libncurses.so.5 had to be symlinked as libncurses.so.6 on Linux. Flashing used st-flash:ツールチェーンの落とし穴:デバッグ設定を hardware reset から software system reset に変更、Linux では libncurses.so.5 を libncurses.so.6 にシンボリックリンク。書き込みは st-flash:

sudo apt-get install stlink-tools
sudo st-flash write <file_to_flash>.bin 0x08000000
sudo st-flash reset

12/22 與 12/24 抄下 STM32F10x 的密度後綴與 startup 檔對照:On 22 and 24 Dec the author copied the STM32F10x density suffixes and matching startup files:12月22日と24日に STM32F10x の密度サフィックスと startup ファイルの対応を書き写した。

後綴Suffixサフィックス意義Meaning意味startup 檔Startup filestartup ファイル
cl互聯型,STM32F105/107Connectivity line, STM32F105/107コネクティビティライン、STM32F105/107startup_stm32f10x_cl.s
vl超值型,STM32F100Value line, STM32F100バリューライン、STM32F100startup_stm32f10x_ld_vl.s / md_vl.s / hd_vl.s
ld低密度,Flash 小於 64 KBLow density, Flash under 64 KB低密度、Flash 64 KB 未満startup_stm32f10x_ld.s
md中密度,Flash 64 或 128 KBMedium density, Flash 64 or 128 KB中密度、Flash 64 または 128 KBstartup_stm32f10x_md.s
hd高密度,Flash 大於 128 KBHigh density, Flash over 128 KB高密度、Flash 128 KB 超startup_stm32f10x_hd.s
xl超高密度,Flash 512 KB 到 1 MBXL density, Flash 512 KB to 1 MB超高密度、Flash 512 KB〜1 MBstartup_stm32f10x_xl.s

無線電:Z-Wave、XBee 與 LoRa 的距離、功耗與廠商比較Radio: Z-Wave, XBee and LoRa range, power and vendor comparison無線:Z-Wave、XBee、LoRa の到達距離、消費電力、ベンダー比較

來源筆記:Source notes: 出典ノート:邊坡種子.md, lora.md

起點是 Z-Wave 廠商的模組。12/5 用 mqtt sub -t ZWARE_TO_MIDDLE 訂閱其 gateway 的事件流,筆記貼了 JSON 樣本:每個事件有 EventType、EventID、Session(UnsolRpt 或 None)、NodeID、ZwClass 95,Status 與 Mode 交替,中間夾著 TX_STS 0 的傳送回報。12/25 距離實測最遠約 40 公尺而非宣稱的 70 公尺,於是提出「是否評估 LoRa」。XBee 發射 3.1 mW;1/6 評估 LoRa 與 XBee 耗電「差不多」。The starting point was the Z-Wave vendor's module. On 5 Dec mqtt sub -t ZWARE_TO_MIDDLE subscribed to its gateway's event stream; the note pastes a JSON sample where each event carries EventType, EventID, Session (UnsolRpt or None), NodeID, ZwClass 95 and alternating Status and Mode, interleaved with TX_STS 0 transmit reports. The 25 Dec range test reached about 40 m, not the claimed 70 m, which raised the question "should we evaluate LoRa?". XBee transmits at 3.1 mW; on 6 Jan LoRa and XBee power draw were judged "about the same".出発点は Z-Wave ベンダーのモジュール。12月5日に mqtt sub -t ZWARE_TO_MIDDLE でゲートウェイのイベントストリームを購読し、ノートに JSON サンプルを貼った。各イベントは EventType、EventID、Session(UnsolRpt または None)、NodeID、ZwClass 95、交互に切り替わる Status と Mode を持ち、間に TX_STS 0 の送信報告が挟まる。12月25日の距離実測は約 40 m で公称 70 m に届かず、「LoRa を評価すべきか」という問いが出た。XBee の送信は 3.1 mW、1月6日に LoRa と XBee の消費電力は「ほぼ同じ」と判断。

1/11 的 LoRa 讀書筆記:擴頻因子 SF7 到 SF12,SF 越大空中時間越長、能耗越高、資料率越低,但距離越遠;SX1301 類 gateway 可多通道多 SF 同時收發,理論上容納約一萬個終端,但多資料率模式限制在 125 kHz × 8 通道;資料率 300 bps 到 37.5 kbps;市區約 5 km、郊區視距 15 km 以上;碰撞應低於總封包的 5 %。正交 SF 讓近的節點用低 SF、遠的用高 SF 換取處理增益。一家台灣 SI 廠的 S76S 模組位元率 146 到 37,500 bps。The 11 Jan LoRa reading notes: spreading factor SF7 to SF12, where a larger SF lengthens time on air, raises energy use and lowers data rate but extends range; an SX1301-class gateway receives on several channels and spreading factors at once and can in theory serve about 10,000 devices, but multi-data-rate mode is limited to 125 kHz times eight channels; data rates 300 bps to 37.5 kbps; about 5 km in cities, 15 km or more rural line of sight; collisions must stay under 5 % of packets. Orthogonal spreading factors let near nodes use a low SF and far nodes a high SF for processing gain. A Taiwanese SI house's S76S module runs at 146 to 37,500 bps.1月11日の LoRa 学習メモ:拡散率 SF7〜SF12、SF が大きいほど空中時間が延び、消費エネルギーが増え、データレートは下がるが到達距離は伸びる。SX1301 級ゲートウェイは複数チャネル・複数 SF を同時受信し理論上約 1 万台を収容するが、マルチデータレートモードは 125 kHz × 8 チャネルに制限。データレート 300 bps〜37.5 kbps、都市部約 5 km、郊外の見通し 15 km 以上、衝突はパケットの 5 % 未満。直交 SF により近くのノードは低 SF、遠くは処理利得のため高 SF。台湾の SI ハウスの S76S モジュールは 146〜37,500 bps。

1/29 的廠商比較如下;RAK 兩三天才回一次、某廠商後來不回應、Advantech 遲未報價。The 29 Jan vendor comparison is below; RAK answered every two or three days, one vendor went silent and Advantech had not quoted.1月29日のベンダー比較を以下に示す。RAK は 2〜3 日に 1 回しか返事がなく、あるベンダーは音信不通、Advantech は見積もり未着。

廠商VendorベンダーGatewayGatewayゲートウェイ節點Nodesノード教育訓練Training教育訓練
AdvantechWISE-6610:防塵不防水,500 節點,每 channel 約 50 到 60WISE-6610: dust-proof not waterproof, 500 nodes, 50 to 60 per channelWISE-6610:防塵・非防水、500 ノード、1 チャネル 50〜60現成戶外型(RS-485 Modbus),未報價Ready-made outdoor (RS-485 Modbus), no quote既製屋外型(RS-485 Modbus)、見積もり未着免費,在高雄Free, in Kaohsiung無料、高雄
台灣 SI 廠Taiwanese SI house台湾の SI ハウス室內 8 通道 8,000 元;室外 16 通道 58,000 元Indoor 8-channel NT$8,000; outdoor 16-channel NT$58,000屋内 8 チャネル 8,000 ドル、屋外 16 チャネル 58,000 ドルLoRa 節點+外殼、MPU-6050+STM32 整成一板,100 pcs 約 31 萬元LoRa node with enclosure, MPU-6050 plus STM32 on one board; 100 pcs about NT$310kLoRa ノード+ケース、MPU-6050+STM32 を 1 枚に統合、100 個で約 31 万ドル22,000 元NT$22,00022,000 ドル
另一家廠商Another vendor別のベンダー室外型 25,000 元Outdoor NT$25,000屋外型 25,000 ドル等報價Quote pending見積もり待ち8,000 元加交通費NT$8,000 plus travel8,000 ドル+交通費

3/5 教育訓練後:LoRa 最遠 25 km,gateway 可接 4G router;兩位同學在 Linux 上架 MQTT broker 重現訓練內容。3/26 STM32 已可直接控制 LoRa 節點,耗電測試開始。埋設實驗兩次:4/9 矽膠乾太慢、天線沒全埋,結果與地表相近;4/16 埋深 30 cm,100 m 掉包約一成、125 m 約 15 %、150 m 跳到 63 %;TX power 16 調到最大 20 多耗六到七成電。耐久測試:payload 4 bytes、每 4 秒一筆,LoRa 約四萬筆、XBee 約 28 萬筆到沒電。後續疑問:RSSI 變化能否當輔助、三個 gateway 只偵測距離改變、溫濕度是否影響 RSSI、兩節點同 channel 看碰撞;5/17 補了 CSMA/CA 與 CSMA/CD 比較。After the 5 Mar training: LoRa reaches 25 km and the gateway can sit behind a 4G router; two labmates set up an MQTT broker on Linux and reproduced the training. By 26 Mar the STM32 drove the LoRa node directly and power testing began. The burial test ran twice: on 9 Apr the silicone dried too slowly, the antenna was not fully covered and the result matched the surface run; on 16 Apr, buried 30 cm, loss was about 10 % at 100 m, 15 % at 125 m and 63 % at 150 m, and raising TX power from 16 to the maximum 20 costs 60 to 70 % more energy. Endurance: a 4-byte payload every 4 s gave about 40,000 LoRa packets versus 280,000 XBee packets before the battery died. Follow-ups: RSSI change as an auxiliary signal, three gateways detecting only a change of distance, whether temperature and humidity shift RSSI, two nodes on one channel to observe collisions; 17 May added a CSMA/CA versus CSMA/CD comparison.3月5日の教育訓練後:LoRa は 25 km 届き、ゲートウェイは 4G ルーターの背後に置ける。仲間 2 人が Linux に MQTT ブローカーを立て訓練内容を再現。3月26日までに STM32 が LoRa ノードを直接制御し消費電力試験が始まった。埋設試験は 2 回:4月9日はシリコーンの乾燥が遅くアンテナが埋まりきらず地表と同じ結果。4月16日、深さ 30 cm で 100 m のロス約 10 %、125 m で 15 %、150 m で 63 %、TX 出力 16→最大 20 で消費 60〜70 % 増。耐久試験:4 バイトを 4 秒ごとに送り、電池切れまで LoRa 約 4 万、XBee 約 28 万パケット。続く疑問:RSSI 変化の補助利用、ゲートウェイ 3 台で距離変化のみ検知、温湿度の RSSI への影響、2 ノード同一チャネルでの衝突観察。5月17日に CSMA/CA と CSMA/CD の比較が加わった。

〈lora.md〉只有三條未解問題:多個 gateway 時 broker 會不會收到同一節點的重複資料?節點 sleep 秒數要大於 10 秒;訂閱者與 broker 不在同一台電腦時怎麼連,Wi-Fi 已被 gateway 占用,是否得靠乙太網路?lora.md holds three unresolved questions: with several gateways, does the broker receive duplicate uplinks from one node? The node's sleep interval must exceed 10 s. And how does a subscriber off the broker host connect, given that Wi-Fi is taken by the gateway link, so is Ethernet required?「lora.md」の未解決の問いは 3 つ:ゲートウェイが複数のときブローカーは同じノードの重複アップリンクを受け取るか。ノードのスリープは 10 秒超。購読者がブローカーと別ホストのときどう接続するか、Wi-Fi はゲートウェイ接続に使われているのでイーサネットが必要か。

關鍵數字:Z-Wave 實測 40 m(宣稱 70 m);LoRa 埋 30 cm 時 100 m 掉包約 10 %、150 m 掉包 63 %;TX power 16→20 多耗 60 到 70 % 電;同樣負載下 XBee 封包數約是 LoRa 的七倍,但 LoRa 的距離才是選它的理由。Key numbers: Z-Wave measured 40 m (70 m claimed); LoRa buried 30 cm loses about 10 % at 100 m and 63 % at 150 m; TX power 16 to 20 costs 60 to 70 % more energy; on the same load XBee sends about seven times as many packets as LoRa, but LoRa's range is what justified it.主要な数値:Z-Wave 実測 40 m(公称 70 m)。LoRa 30 cm 埋設で 100 m ロス約 10 %、150 m で 63 %。TX 出力 16→20 で消費 60〜70 % 増。同じ負荷で XBee のパケット数は LoRa の約 7 倍だが、LoRa を選んだ理由は到達距離。

演算法:從數零交叉到 Mahony AHRS 與位移積分Algorithm track: from counting zero crossings to Mahony AHRS and displacement integrationアルゴリズム:ゼロ交差の計数から Mahony AHRS と変位積分へ

來源筆記:Source notes: 出典ノート:邊坡種子.md

指導教授 12/4 的限制很硬:演算法不要有乘法(耗電),連濾波器都不要,只要分出振動、滑動、旋轉和其他。振動看訊號與 baseline 的交叉次數,旋轉靠陀螺儀,剩下滑動與其他。作者隨即問:振動加滑動若只判成振動,漏掉滑動行嗎?這就是他的 2×2×2 八種狀況矩陣。12/25 已能用波峰數(速度斜率為 0、加速度跨零)超過門檻偵測振動,但也發現旋轉會改變加速度 baseline(重力分量而非真實線性加速度),原地旋轉會被判成滑動,所以需要陀螺儀修正;修正要大量數學,但節點平常在 stop mode,瞬間耗電應可接受。1/6 教授列出三種實作:從穩定起點到終點畫斜線當 offset 扣掉、用陀螺儀算、用最精準最多數學的方法算。The advisor's 4 Dec constraints were strict: no multiplications (they cost energy), not even a filter; just tell vibration, sliding, rotation and "other" apart. Vibration is counted as crossings of the baseline, rotation goes to a gyro, and sliding versus other remains. The author asked at once: if vibration plus sliding is classed as vibration only, is missing the slide acceptable? That is his 2 × 2 × 2 matrix of eight cases. By 25 Dec vibration was detected by counting peaks (velocity slope zero, acceleration crossing zero) against a threshold, but rotation was found to shift the acceleration baseline (the gravity component, not real linear acceleration), so rotating in place looks like sliding and a gyro correction is needed; it takes much arithmetic, yet since the node sits in stop mode most of the time the brief burst seemed acceptable. On 6 Jan the advisor listed three implementations: draw a line from stable start to stable end and subtract it as offset; compute with the gyro; compute with the most precise, math-heavy method.12月4日の指導教授の制約は厳しかった。乗算なし(電力を食う)、フィルターすら無し、振動・滑動・回転・その他を区別できればよい。振動はベースラインとの交差回数、回転はジャイロ、残りが滑動かその他か。著者はすぐ問うた。振動+滑動を振動だけと分類し滑動を見逃してよいのか。これが 2×2×2 の 8 ケース行列だ。12月25日までにピーク数(速度の傾きゼロ、加速度のゼロ交差)の閾値判定で振動を検出できたが、回転が加速度のベースライン(実際の線形加速度ではなく重力成分)を変え、その場回転が滑動に見えるためジャイロ補正が要ると分かった。計算は多いが、ノードは普段 stop モードなので瞬間的消費は許容と考えた。1月6日に教授は 3 つの実装を挙げた。安定した始点から終点へ直線を引きオフセットとして引く、ジャイロで計算、最も精密で数学の多い方法で計算。

1 月是姿態估計的學習期:陀螺儀用 Kalman(TKJ Electronics 的實作文)、Kalman 五大公式、四元數與歐拉角、互補濾波,以及 1/8 抄的協方差複習(協方差 0 表示線性無關但非獨立)。1/22 結論:穩態時用加速規修正姿態再進 stop mode,但重力與 z 軸平行時 yaw 仍得靠陀螺儀或磁力計;重力補償先繞 x 軸再繞 y 軸。1/29 記下兩個未解問題:同一姿態用不同旋轉順序(絕對座標 x→z→x→y (0, 90, −90) 與相對座標 x→y→z→y (90, 0, −90))結果不一致,因為旋轉軸不同而先前推導當成同一軸;以及積分無法歸零。2/19 找到文獻修正:原本用的是慣性座標系的角速度,改用 body frame 的角速度後,四元數畫出的重力變化就正確了。January was spent learning attitude estimation: Kalman filtering for the gyro (the TKJ Electronics write-up), the five Kalman equations, quaternions and Euler angles, complementary filtering, and a covariance refresher copied on 8 Jan (zero covariance means no linear relation, not independence). The 22 Jan conclusion: correct attitude with the accelerometer at steady state, then enter stop mode; when gravity is parallel to z, yaw still depends on the gyro or a magnetometer; gravity compensation rotates about x first, then y. On 29 Jan two open problems were logged: the same pose reached by different rotation orders (absolute frame x→z→x→y at (0, 90, −90) versus relative frame x→y→z→y at (90, 0, −90)) gave different results because the rotation axes differ while the derivation had assumed one axis; and the integral would not return to zero. On 19 Feb the fix was found in the literature: the code had used the angular rate in the inertial frame; with the body-frame rate the gravity trace drawn from the quaternion came out right.1 月は姿勢推定の学習期:ジャイロの Kalman(TKJ Electronics の記事)、Kalman の 5 式、四元数とオイラー角、相補フィルター、1月8日に写した共分散の復習(共分散ゼロは線形無関係であって独立ではない)。1月22日の結論:定常状態で加速度計により姿勢を補正してから stop モードへ、重力が z 軸と平行なら yaw はジャイロか磁力計に頼る、重力補償は x 軸回りの後に y 軸回り。1月29日に未解決問題を 2 つ記録:同じ姿勢を異なる回転順序(絶対座標 x→z→x→y の (0, 90, −90) と相対座標 x→y→z→y の (90, 0, −90))で到達すると回転軸が違うため結果が一致せず、導出は同一軸を仮定していた。そして積分がゼロに戻らない。2月19日に文献から修正を見つけた。コードは慣性系の角速度を使っていたが、body フレームの角速度にすると四元数から描いた重力の軌跡が正しくなった。

舊演算法還有更深的問題:磁力計繞 z 軸轉 360° 的原始數據是歪的橢圓而非圓;找不到可靠資料教 Kalman 用在 yaw(找到的都被評為錯誤並建議 AHRS);pitch 或 roll 不為 0 時繞 yaw 一圈,積分差幾十度不歸零。於是轉向 x-io 的開源 AHRS:Mahony 濾波器(沒磁力計也能算,有更準;另有 Madgwick)。3/5 起分工:一位同學調 Mahony 的 PI 參數(試誤法,不行再加 D)、做磁力計橢圓擬合、說明「追逐重力 {0, 0, 1} 與磁力平面只有 x 分量」的程式;另一位接手 GUI,把線性加速度(加速規量測值減估出的重力)轉大地座標並兩次積分畫軌跡。程式碼在一位同學的 GitHub(mpu9250_mahony)。The old algorithm had deeper problems: the magnetometer's raw data over a 360° turn about z was a skewed ellipse rather than a circle; no reliable source explained Kalman filtering of yaw (those found were judged wrong, with AHRS recommended); and with pitch or roll non-zero, one full yaw turn left tens of degrees of integration error. So the team moved to x-io's open-source AHRS: the Mahony filter (works without a magnetometer, better with one; Madgwick is the alternative). From 5 Mar one labmate tuned the Mahony PI gains (trial and error, a D term if needed), fitted the magnetometer ellipse and documented the code as "chasing gravity {0, 0, 1} and a magnetic plane with only an x component"; another took the GUI and converted linear acceleration (accelerometer reading minus estimated gravity) to the earth frame with double integration to draw a trajectory. The code lives in a labmate's GitHub repository (mpu9250_mahony).旧アルゴリズムにはもっと深い問題があった。磁力計の z 軸回り 360° の生データは円ではなく歪んだ楕円。yaw の Kalman 適用を説明する信頼できる資料が無い(見つけたものは誤りとされ AHRS が推奨)。pitch か roll がゼロでない状態で yaw を一周すると数十度の積分誤差が残る。そこで x-io のオープンソース AHRS へ移行:Mahony フィルター(磁力計なしでも動き、あればより正確。代替は Madgwick)。3月5日からの分担:1 人が Mahony の PI ゲイン調整(試行錯誤、必要なら D 追加)、磁力計の楕円フィッティング、「重力 {0, 0, 1} と x 成分のみの磁気平面を追う」コードの解説。もう 1 人が GUI を引き継ぎ、線形加速度(加速度計の読みから推定重力を引いたもの)を地球座標系に変換し二重積分で軌跡を描く。コードは仲間の GitHub リポジトリ(mpu9250_mahony)にある。

3/26 承認各種濾波調到最後「像先射箭再畫靶」。4/9 積分仍不理想:靜止時加速度有時歸零有時不歸零;候選方法有高低通濾波、加速度低於門檻就把速度歸零(ZUPT)、ZVU,或直接分析線性加速度而不求位移。4/16 用 x-io 的 Gait-Tracking-With-x-IMU MATLAB 程式(去掉重力方向 z)實驗:x 方向純位移 30 cm 抓得到;x 方向純振動 10 cm 位移會「炸開」。計畫跑兩套演算法:一套抓振動(兩次高通濾波),一套抓位移,並用新的 ZVU(參考加速度向量長度與角速度)歸零速度。殘餘重力約 0.1 g 排不掉且會讓積分炸開,有時 reset 後又正常,疑是加速規本身的問題;該步行演算法也是為人類步態設計的。On 26 Mar the author admitted that tuning filter after filter felt like "shooting the arrow first and painting the target around it". On 9 Apr integration was still poor: at rest the acceleration sometimes returned to zero and sometimes not. Candidates were high- and low-pass filtering, zeroing velocity when acceleration falls below a threshold (ZUPT), ZVU, or analysing linear acceleration directly without displacement. On 16 Apr the x-io Gait-Tracking-With-x-IMU MATLAB script was tried with the gravity axis z removed: pure displacement of 30 cm along x was recovered; pure vibration of 10 cm along x made the displacement "explode". The plan became two algorithms, one for vibration (two high-pass filters in series) and one for displacement, with a new ZVU that resets velocity from the acceleration-vector length and the angular rate. About 0.1 g of residual gravity could not be removed and blew up the integral; a reset sometimes cured it, pointing at the accelerometer itself; and the gait script is designed for human walking anyway.3月26日、著者はフィルターを次々に調整するのは「先に矢を射てから的を描くようだ」と認めた。4月9日も積分は不良で、静止時に加速度がゼロに戻ることも戻らないこともあった。候補はハイパス・ローパス、加速度が閾値未満なら速度をゼロにする(ZUPT)、ZVU、または変位を求めず線形加速度を直接解析。4月16日に x-io の Gait-Tracking-With-x-IMU MATLAB スクリプトを重力軸 z を除いて試した:x 方向 30 cm の純粋な変位は復元できた。x 方向 10 cm の純粋な振動では変位が「爆発」。計画は振動用(ハイパス 2 段)と変位用の 2 アルゴリズムに分かれ、加速度ベクトルの長さと角速度で速度をリセットする新しい ZVU を使う。約 0.1 g の残留重力は除去できず積分を発散させ、リセットで直ることもあり加速度計自体を疑った。そもそもこの歩行スクリプトは人間の歩行向けだ。

最關鍵的現場事實(12/25):台 20 線 52K 一年的滑動以公分為單位,加速規量不到這麼微小的加速度;雲端側教授建議改裝在更可能大幅滑動的地點。5/31 的方向是以 1 m 當臨界點判斷,5/17 則提到拉高門檻、決策樹與神經網路。The most important field fact (25 Dec): yearly sliding at Highway 20, 52K is measured in centimetres, far too small for the accelerometer to see; the cloud-side professor suggested installing where large slides are likelier. By 31 May the plan was a 1 m decision threshold; on 17 May raising thresholds, decision trees and neural networks were floated.最も重要な現場の事実(12月25日):省道 20 号線 52K の年間滑動はセンチメートル単位で、加速度計には小さすぎる。クラウド側教授は大きな滑りが起きやすい場所への設置を提案。5月31日には 1 m を判定閾値とする方針、5月17日には閾値引き上げ、決定木、ニューラルネットワークも挙がった。

專家諮詢(2021 年 6 月):測量系、土木系與第三位教授的建議Expert consultations (June 2021): surveying, civil engineering and a third professor専門家への相談(2021年6月):測量学科、土木学科、第三の教授

來源筆記:Source notes: 出典ノート:邊坡種子.md

測量系教授的回信先問「振動是高頻、位移是低頻,接下來怎麼處理?」並說「GPS 似乎是最佳解」,建議把邊坡既有的 GPS 資料微分成加速度看訊號特徵。6/11 視訊更具體:他們做的非常類似,也是多點布設 GPS 在同一座隧道;IMU 靜止時的重力 drift 要用擬合函式校正,概念像磁場橢圓擬合,校正前先觀察靜止狀態約一週;注意 common-mode 誤差;多點資料送到雲端一起分析才有意義;曾與資工系用無線訊號相位差判斷位移,因跳頻與精度不佳而失敗。The surveying professor's reply first asked "vibration is high-frequency, displacement low-frequency, so what next?", said "GPS seems to be the best answer", and suggested differentiating the slope's existing GPS records into acceleration to study their signature. The 11 Jun video call went further: their group does something very similar, a multi-point GPS array at the same tunnel; gravity drift of a static IMU should be corrected with a fitted function, much like the magnetometer ellipse fit, after observing the sensor at rest for about a week; watch for common-mode error; multi-node data only becomes meaningful when fused in the cloud; and a joint attempt with the computer-science department to measure displacement from wireless-signal phase differences failed on frequency hopping and poor precision.測量学科教授の返信はまず「振動は高周波、変位は低周波、ではどう扱うか」と問い、「GPS が最善の解に見える」と述べ、斜面の既存 GPS 記録を微分して加速度にし特徴を調べるよう勧めた。6月11日のビデオ会議はさらに具体的:彼らも非常に似たことをしており、同じトンネルに多点 GPS を配置。静止 IMU の重力ドリフトは磁力計の楕円フィッティングに似た当てはめ関数で補正し、その前に約 1 週間静止状態を観察。コモンモード誤差に注意。多点データはクラウドで統合して初めて意味を持つ。情報工学科と無線信号の位相差で変位を測る試みは周波数ホッピングと精度不足で失敗。

土木系第一位教授(擁有振動平台者)建議地震預警常用的貝氏分類:多節點兩兩一組,不需量到位移;並說不到十公尺深大地工程的人較難接受。作者的反思:我們只是要做滑動監測與告警,不是大地工程要的預測。第二位土木系教授說明傳統工具是埋在地盤中的傾度管搭配傾斜儀(積分得各深度相對管底的水平位移)與量坡面兩點相對位移的伸張儀,並透露曾詢問的廠商 IMU 是軍規品已不能輸入台灣。第三位教授(8/13)提出用錯誤率偵測距離,可到公分等級;第一年先埋設觀察訊號,才知道怎麼把錯誤率對應到距離。The first civil-engineering professor (the one with the shake table) suggested Bayesian classification as used in earthquake early warning: many nodes in pairs, no displacement measurement needed; he warned that geotechnical people distrust anything shallower than ten metres. The author's reflection: the target is slide monitoring and alarms, not the prediction geotechnical engineering wants. The second civil-engineering professor explained that the conventional tools are inclinometer casings in the ground read with a probe (integrated to give horizontal displacement at each depth relative to the casing bottom) and extensometers between two surface points, and revealed that a vendor's IMU he had asked about was military-grade and can no longer be imported into Taiwan. A third professor (13 Aug) described ranging by error rate, reaching centimetre level; bury nodes in year 1 and observe the signal first, then map error rate to distance.土木学科の最初の教授(振動台を持つ人物)は地震早期警報で使われるベイズ分類を提案:多数のノードを 2 つずつ組にし、変位測定は不要。深さ 10 m 未満は地盤工学の人に受け入れられにくいとも警告。著者の省察:目的は滑動の監視と警報であり、地盤工学が求める予測ではない。2 人目の土木学科教授は、従来の道具は地盤に埋めるインクリノメーター管とプローブ(積分して管底に対する各深度の水平変位を得る)と地表 2 点間の伸縮計だと説明し、問い合わせたベンダーの IMU が軍用グレードで台湾へもう輸入できないことも明かした。3 人目の教授(8月13日)は誤り率による測距を説明し、センチメートル級に達する。1 年目にノードを埋めてまず信号を観察し、後で誤り率を距離に対応づける。

專案管理:審查期限、雲端側工作、BOM 交接與時程Project management: review deadlines, the cloud side, the BOM hand-off and the timelineプロジェクト管理:審査期限、クラウド側、BOM の引き渡し、タイムライン

來源筆記:Source notes: 出典ノート:邊坡種子.md

雲端與派遣側的工作 12/4 分派:Flask 後端供前端測試、改 MariaDB、AJAX 撈 xyz、Google Maps、假資料;1/8 要求告警要收到 e-mail;1/18 規劃 gateway 之後串雨量感測器;8/27 詢價雨量計並問土壤計能否整顆埋入;6/4 提醒每月 Google API 費用要估進預算。審查節奏:1/20 要有影片;2/22 定 3/15 為完成品 demo、三月中 review、word 報告四月底上傳;3/22 作者彙整不超過 15 頁的投影片;3/29 提示:第一頁結構圖、第二頁研究目的、經費用表格、主要困難放附錄、影片少講技術細節。4/14 報告要用小批量生產預算與實際續航實驗。與 Z-Wave 廠商的量產討論 6/28 開始,要給 BOM 與種子規格;7/12 與 7/26 都在催 BOM,否則談不下去。其他待辦:向科技部承辦人確認第二期與應繳報告(不要「直接」問有沒有第二次審查會);聯絡公路總局第五區養護工程處與曾文工務段,邀高工局南分局開座談會爭取經費。Cloud and dispatch tasks were assigned on 4 Dec: a Flask backend for front-end testing, a move to MariaDB, pulling xyz data with AJAX, Google Maps, fake data. On 8 Jan alarms had to arrive by e-mail; on 18 Jan rainfall sensors were planned behind the gateway; on 27 Aug rain gauges were priced and a vendor asked whether its soil probe could be buried whole; on 4 Jun the monthly Google API fee was flagged for the budget. Review rhythm: a video by 20 Jan; on 22 Feb the 15 Mar demo was fixed, with a mid-March review and the Word report uploaded end of April; on 22 Mar the author consolidated a deck of at most 15 slides; the 29 Mar notes: architecture diagram on page one, research goals on page two, budget as a table, main difficulties in the appendix, less technical detail in the video. The 14 Apr report needed the small-batch budget and a real endurance test. Production talks with the Z-Wave vendor began 28 Jun with the BOM and seed specification to hand over; the BOM was chased on 12 and 26 Jul since nothing could move without it. Other to-dos: confirm a second phase and the reports still due with the science-ministry officer (not asking "directly" about a second review); reach the Highway Bureau's 5th maintenance office and the Zengwen section office and invite the freeway bureau's southern branch to a workshop to seek funding.クラウドと派遣側のタスクは 12月4日に割り当て:フロントエンド試験用の Flask バックエンド、MariaDB への移行、AJAX で xyz 取得、Google Maps、ダミーデータ。1月8日に警報のメール受信、1月18日にゲートウェイの先の雨量センサー計画、8月27日に雨量計の見積もりと土壌プローブを丸ごと埋められるかの質問、6月4日に毎月の Google API 料金を予算に入れる注意。審査のリズム:1月20日までに動画。2月22日に 3月15日のデモを確定、3月中旬レビュー、Word 報告は 4月末アップロード。3月22日に著者は最大 15 枚のスライドにまとめた。3月29日のメモ:1 ページ目は構成図、2 ページ目は研究目的、予算は表、主な困難は付録、動画は技術的細部を減らす。4月14日の報告には小ロット予算と実際の耐久試験が必要。Z-Wave ベンダーとの量産協議は 6月28日に開始し BOM とシード仕様を渡す。BOM がないと進まないため 7月12日と26日に催促。その他の ToDo:科学技術部の担当者に第 2 期と残りの報告を確認(第 2 回審査の有無を「直接」聞かない)、公路総局第五区養護工程処と曽文工務段に連絡し高速公路局南区分局を座談会に招いて資金を求める。

日期Date日付里程碑Milestoneマイルストーン
2020-11-20啟動:提案、量產經費、專利Kick-off: proposal, production budget, patentキックオフ:提案、量産予算、特許
2020-12-01參訪 Z-Wave 廠商Z-Wave vendor visitZ-Wave ベンダー訪問
2020-12-18台 20 線 52K 場勘Site survey at Highway 20, 52K省道 20 号線 52K の現地調査
2020-12-25stop mode 喚醒完成;Z-Wave 40 m;振動偵測可行;滑動只有公分級Stop-mode wake-up done; Z-Wave 40 m; vibration detection works; sliding only centimetresstop 起床完了、Z-Wave 40 m、振動検出が動作、滑動はセンチ級
2021-01-29LoRa 廠商比較表LoRa vendor comparisonLoRa ベンダー比較
2021-02-19body-frame 角速度修正;轉向 Mahony AHRSBody-frame angular-rate fix; move to Mahony AHRSbody フレーム角速度の修正、Mahony AHRS へ
2021-03-05LoRa 教育訓練;Mahony demoLoRa training; Mahony demoLoRa 教育訓練、Mahony デモ
2021-03-15完成品 demo(審查)Finished-product demo (review)完成品デモ(審査)
2021-04-16埋深 30 cm 掉包率;MATLAB 步態實驗30 cm burial loss figures; MATLAB gait experiment30 cm 埋設のロス数値、MATLAB 歩行実験
2021-06-11與測量系教授視訊;會計規則Video call with the surveying professor; accounting rules測量学科教授とビデオ会議、会計ルール
2021-06-28與 Z-Wave 廠商談量產,要 BOMProduction talks with the Z-Wave vendor, BOM requestedZ-Wave ベンダーと量産協議、BOM 要求
2021-10-04採購清單:PCB 100、種子 50、土壤溼度計 30Purchase list: 100 PCBs, 50 seeds, 30 soil-moisture probes購入リスト:PCB 100、シード 50、土壌水分計 30

作者留下的開放問題與教訓Open questions and lessons the author recorded著者が残した未解決の問いと教訓

來源筆記:Source notes: 出典ノート:邊坡種子.md, lora.md

  • 感測能力與現象尺度不合:一年幾公分的潛移加速規看不見;專家一致指向 GPS、多點融合與貝氏配對判斷,而非單顆 IMU 積分位移。Sensor and phenomenon do not match in scale: creep of a few centimetres a year is invisible to an accelerometer; every expert pointed to GPS, multi-node fusion and Bayesian paired decisions rather than integrating displacement from one IMU.センサーと現象のスケールが合わない。年に数センチのクリープは加速度計には見えず、専門家は皆、単一 IMU の変位積分ではなく GPS、多点融合、ベイズ的なペア判定を指した。
  • 「不要乘法、不要濾波」與後來的 Mahony、兩段高通、ZUPT 路線明顯衝突,筆記沒記錄如何收場。The "no multiplications, no filters" constraint conflicts with the later Mahony, double high-pass and ZUPT path; the note never records how that was resolved.「乗算なし、フィルターなし」の制約は後の Mahony、二段ハイパス、ZUPT の路線と衝突するが、どう決着したかの記録はない。
  • 振動加滑動的八種組合、靜止時加速度為何有時不歸零、磁力計橢圓的來源、yaw 的 Kalman 修正,都停在「??」。The eight vibration-plus-sliding cases, why acceleration at rest sometimes fails to return to zero, the origin of the magnetometer ellipse and Kalman correction of yaw all stopped at "??".振動+滑動の 8 通り、静止時に加速度がゼロに戻らない理由、磁力計の楕円の原因、yaw の Kalman 補正は、いずれも「??」で止まっている。
  • 無線側未決:多 gateway 的重複上行、訂閱者不在 broker 主機時的網路路徑、同 channel 碰撞率、RSSI 或錯誤率能否輔助測距、天線能否全埋。Radio questions left open: duplicate uplinks with several gateways, the network path when the subscriber is off the broker host, same-channel collision rate, RSSI or error rate as auxiliary ranging, and whether the antenna can be fully buried.無線側の未決:複数ゲートウェイでの重複アップリンク、購読者がブローカーと別ホストの場合の経路、同一チャネルの衝突率、RSSI や誤り率の補助測距、アンテナの完全埋設。
  • 管理教訓:第一年結餘不會滾入第二年;發票拆分與財產標籤規則要在採購前弄清;BOM 沒交出去量產談判就停擺。Management lessons: the first-year leftover does not roll over; invoice-splitting and asset-tag rules must be understood before buying; production talks stall until the BOM is delivered.管理面の教訓:1 年目の残額は繰り越せない。請求書の分割と資産ラベルのルールは購入前に理解する。BOM を渡すまで量産協議は止まる。
回到頂端 ↑Back to top ↑ページ上部へ ↑

智慧交通:台南公車與緊急車輛號誌優先的 RSU 開發筆記Smart transport: RSU development notes for Tainan bus and emergency-vehicle signal priorityスマート交通:台南のバス・緊急車両信号優先システムの RSU 開発ノート

五篇筆記圍繞同一個案子:台南市的公車號誌優先(TSP)與緊急車輛號誌優先(EVSP)。時間從 2020 年 9 月的架構會議到 2021 年 10 月的補償邏輯,內容有作者初讀通訊層程式的筆記、中介層與應用層的運作、兩家號控箱廠牌的差異、作者實作的功能、路口實驗檢核表和同事離職的交接。最大的 智慧交通的code.md 近 48 KB;本節依主題整理。Five notes orbit one project: Tainan's transit signal priority (TSP) for buses and emergency-vehicle signal priority (EVSP). They run from architecture meetings in September 2020 to compensation logic in October 2021 and cover the author's first reading of the communication-layer code, the middleware and application layer, two controller brands, the features the author built, a field checklist and a colleague's handover. The largest note, 智慧交通的code.md, is close to 48 KB; this section is grouped by theme.五つのノートは同じ案件、台南市のバス信号優先(TSP)と緊急車両信号優先(EVSP)を扱う。2020 年 9 月のアーキテクチャ会議から 2021 年 10 月の補償ロジックまでを記録し、通信層コードの初読ノート、ミドルウェアとアプリケーション層、二つの制御器メーカー、著者が作った機能、現場チェックリスト、同僚の引き継ぎを含む。最大の 智慧交通的code.md は 48 KB 近い。本節はテーマ別に整理する。

系統全貌:雲端、RSU、號控箱與 OBUSystem shape: cloud, RSU, TC box and OBUシステムの全体像:クラウド、RSU、信号制御器、OBU

來源筆記:Source notes: 出典ノート:智慧運輸.md, 智慧交通的code.md

每個路口有一台路側單元(RSU),實體是工業電腦(IPC),同時講三種語言:透過跑 oslink 的 DSRC 盒子以 802.11p 和車上 OBU 溝通、以 4G 連雲端、以序列協定驅動號誌控制箱(TC 箱)。程式裡 RSU 是伺服器,雲端是連入的客戶端。軟體分通訊層、中介層、應用層,應用層有 TSP 與 EVSP 兩支 app;分工也循此:一位同學寫通訊層,一位負責中介層與應用層骨架,一位負責 EVSP 邏輯與設定,雲端由合作廠商負責,作者 2021 年春加入,讀程式、加功能、跑現場。控制分兩階:一階的策略由 RSU 外部(同學的規劃程式)產生,RSU 只執行;二階由 RSU 查自己的「supermatrix」表。網頁地圖上二階路口是灰色,一階是半透明淡藍色。OBU 分 hosted 與 hostless,會議反覆追問 hostless 是否存在,最後定義為「hostless 等於外接 IPC」。Each intersection has a roadside unit (RSU), an industrial PC (IPC) that speaks three languages: DSRC 802.11p to vehicle OBUs through a DSRC box running oslink, 4G to the cloud, and a serial protocol to the traffic-controller cabinet (TC box). In the code the RSU is the server and the cloud connects in as a client. The software has a communication layer, a middleware and an application layer with two apps, TSP and EVSP, and ownership followed the layers: one labmate wrote the com layer, another owned the middleware and application scaffolding, a third owned the EVSP logic and config, the cloud belonged to a partner company, and the author joined in spring 2021 to read the code, add features and run field work. Control has two stages: in the first the strategy comes from outside the RSU (a labmate's planner) and the RSU only executes it; in the second the RSU looks up its own "supermatrix" table. The web map drew second-stage intersections grey and first-stage ones translucent light blue. OBUs are hosted or hostless; meetings kept asking whether hostless existed and settled on "hostless means an external IPC".各交差点には路側機(RSU)、すなわち産業用 PC(IPC)があり、三つの言語を話す。oslink を動かす DSRC ボックス経由で 802.11p により車載器(OBU)と、4G でクラウドと、シリアルプロトコルで信号制御器(TC ボックス)と通信する。コード上では RSU がサーバで、クラウドがクライアントとして接続する。ソフトウェアは通信層、ミドルウェア、アプリケーション層からなり、後者には TSP と EVSP の二つのアプリがある。担当もこの層に沿い、通信層は研究室の一人、ミドルウェアとアプリケーションの骨組みは別の一人、EVSP のロジックと設定は三人目、クラウドは協力企業で、著者は 2021 年春に加わりコード理解、機能追加、現場作業を担った。制御は二段階で、第一段階では戦略を RSU の外(研究室メンバーのプランナー)で生成し RSU は実行だけを行い、第二段階では RSU 自身が「supermatrix」表を引く。Web 地図では第二段階の交差点が灰色、第一段階が半透明の薄い青だった。OBU には hosted と hostless があり、会議では hostless の存在が繰り返し問われ、「hostless とは外付け IPC」と定義された。

智慧運輸.md(2020 年 9 月到 12 月)記錄了架構爭論。OBU 廠商的 V2X API 用 JSON 檔加 C API 設定 caster id、PSID(1609.3 的識別碼)與安全性;不開 raw data 時 API 會填 BSM 欄位,開了就不會。API 藏起 socket fd、底層走 ZeroMQ,於是問題一串:request-reply 還是 pub-sub?zmq context 是什麼?能否拿一般 TCP 直連 zmq socket(不行)?zmq 會不會把 TCP 合併的封包切開(用 no-Nagle 處理)?後來通訊層的同學把 zmq 整個拿掉。6/8 的會議補上標準:SAE J2735 是訊息載具,J2945 是更高層的應用規範,智慧 AVI 設備會走它把資料丟給 RSU。智慧運輸.md (September to December 2020) records the architecture debates. The OBU vendor's V2X API sets caster id, PSID (the 1609.3 identifier) and security through a JSON file plus a C API; with raw data off it fills in BSM fields, with raw data on it does not. The API hides the socket fd and rides on ZeroMQ, which raised a string of questions: request-reply or pub-sub, what a zmq context is, whether plain TCP may talk to a zmq socket (no), and whether zmq re-splits packets TCP has coalesced (turn Nagle off). The com-layer owner later dropped zmq entirely. The 6/8 meeting added the standards: SAE J2735 is the message carrier, J2945 the higher-level application profile, and the smart AVI device would use it to push data into the RSU.智慧運輸.md(2020 年 9 月〜12 月)はアーキテクチャの議論を記録する。OBU ベンダの V2X API は JSON ファイルと C API で caster id、PSID(1609.3 の識別子)、セキュリティを設定し、raw data 無効なら BSM フィールドを埋め、有効なら埋めない。API はソケット fd を隠し下層は ZeroMQ で、疑問が連なった。request-reply か pub-sub か、zmq context とは何か、素の TCP で zmq ソケットに接続できるか(できない)、TCP が結合したパケットを zmq が分割するか(no-Nagle で対処)。のちに通信層の担当者は zmq を丸ごと外した。6/8 の会議では規格も整理された。SAE J2735 はメッセージの運搬役、J2945 は上位のアプリケーション仕様で、スマート AVI 機器はこれで RSU にデータを渡す。

通訊層:Redis 風格的 ae 事件迴圈The communication layer: a Redis-style ae event loop通信層:Redis 風の ae イベントループ

來源筆記:Source notes: 出典ノート:智慧交通的code.md, 智慧運輸.md

通訊層是 Redis 風格的 ae 事件迴圈,由四個結構撐起:ae_comm_event(READABLE/WRITABLE 遮罩、讀寫回呼、clientData)、ae_fired_event(fd 加遮罩)、ae_time_event(計時器鏈結串列)和 ae_event_loop(已註冊與已觸發事件陣列、epoll 資料、計時器串列頭、last_time、睡前回呼)。作者的解讀:fired event 就是 epoll_wait 回傳的事件,clientData 就是回呼裡轉型回來的 client_t,它持有 fd、com_id、讀寫緩衝區和負責實際收送的 handle。客戶端存在以 com_id 為鍵的雜湊表,所以 com_send 用 comm_dict_find 找客戶端,作者推測只是為了查找速度。com_send 是唯一 dequeue 的地方,它不直接寫 socket,而是建立 com event(TCP、UDP 各一種),等迴圈處理時才呼叫寫回呼。ae_create_comm_event 在 TCP 與 UDP 的 accept handler、兩者內部的讀端註冊和 com_send 裡共被呼叫五次。監聽 socket 設成 non-blocking,沒資料就回錯誤,不會卡住迴圈。The com layer is a Redis-style ae event loop carried by four structs: ae_comm_event (a READABLE/WRITABLE mask, read and write handlers, clientData), ae_fired_event (fd plus mask), ae_time_event (a linked list of timers) and ae_event_loop (registered and fired event arrays, epoll data, the timer list head, last_time and a before-sleep hook). The author's reading: fired events are what epoll_wait returned, and clientData is the client_t cast back inside the callback; it holds the fd, com_id, read and write buffers and a handle whose recv and send functions do the real work. Clients live in a hash table keyed by com_id, so com_send finds a client with comm_dict_find, presumably just for lookup speed. com_send is the only place that dequeues; it does not write the socket but creates a com event (one for TCP, one for UDP) whose write callback runs when the loop gets to it. ae_create_comm_event is called five times in all: in the TCP and UDP accept handlers, once more inside each for the read side, and twice in com_send. The listening sockets are non-blocking, so an empty read returns an error instead of stalling the loop.通信層は Redis 風の ae イベントループで、四つの構造体が支える。ae_comm_event(READABLE/WRITABLE マスク、読み書きハンドラ、clientData)、ae_fired_event(fd とマスク)、ae_time_event(タイマーの連結リスト)、ae_event_loop(登録済みと発火済みのイベント配列、epoll データ、タイマーリスト先頭、last_time、スリープ前フック)。著者の読み:fired event は epoll_wait が返したイベントで、clientData はコールバック内でキャストし直す client_t であり、fd、com_id、読み書きバッファ、実際の送受信を担う handle を持つ。クライアントは com_id をキーとするハッシュテーブルにあり、com_send は comm_dict_find で引く。著者の推測では検索速度のためだけである。com_send は dequeue する唯一の場所で、ソケットに直接書かず com event(TCP 用と UDP 用)を作り、ループが処理する時点で書き込みコールバックが走る。ae_create_comm_event は TCP と UDP の accept ハンドラ、その内部の読み取り側登録、com_send 内で合計五回呼ばれる。リッスンソケットは non-blocking で、データがなければエラーを返しループを止めない。

兩個設計決定很突出。TCP accept handler 會把前一個雲端連線標為「expired」並殺掉,永遠只保持一條雲端連線;UDP 沒有這機制,因為它根本不會斷線。UDP(DSRC 側)用自訂 net_UDP_accept:固定 fd 接新連線,再給每個裝置一個新 fd;它的讀回呼多呼叫 comm_packet_enqueue(client, FROM_DSRC)。time event 只在兩處建立,都為了處理雲端斷線:回呼把 id 標成過期、把錯誤訊息送進佇列。ae_delete_time_event 只把 id 設為 −1,是 lazy delete;新計時器採頭插。若 now 早於 last_time 就視為時鐘偏移,把所有計時器的 when_sec 歸零。Two design decisions stand out. The TCP accept handler marks the previous cloud connection "expired" and kills it, so only one cloud connection ever exists; UDP has no such mechanism because it never disconnects. UDP (the DSRC side) uses a custom net_UDP_accept: a fixed fd takes new connections, then each device gets its own fresh fd; its read callback additionally calls comm_packet_enqueue(client, FROM_DSRC). Time events are created in exactly two places, both for cloud disconnection: the callback marks the id expired and pushes an error message onto the queue. ae_delete_time_event only sets the id to −1, a lazy delete; new timers go in at the list head. If now is earlier than last_time the loop treats it as clock skew and zeroes every timer's when_sec.二つの設計判断が際立つ。TCP の accept ハンドラは前のクラウド接続を「expired」にして殺すので、クラウド接続は常に一本だけ。UDP にはその仕組みがない。そもそも切断しないからだ。UDP(DSRC 側)は独自の net_UDP_accept を使い、固定 fd で新規接続を受けて各デバイスに新しい fd を与える。その読み取りコールバックは comm_packet_enqueue(client, FROM_DSRC) も呼ぶ。time event はちょうど二か所で作られ、どちらもクラウド切断処理のためで、コールバックは id を期限切れにしエラーメッセージをキューに入れる。ae_delete_time_event は id を −1 にするだけの遅延削除で、新タイマーはリスト先頭に挿入される。now が last_time より前なら時刻のずれとみなし、全タイマーの when_sec をゼロにする。

typedef struct ae_time_event {
    long long id;                 /* time event id; -1 = lazily deleted */
    long when_sec;                /* seconds      */
    long when_ms;                 /* milliseconds */
    ae_time_process *time_proc;
    ae_event_time_destructor *destructor_proc;
    void *clientData;
    struct ae_time_event *next;
} ae_time_event;

#define BIT(n)      (1UL << (n))
#define BIT_MASK(n) (BIT(n) - 1)

留下的疑問:ae_delete_time_event 真正的用途、handle 裡複雜的 recv_fn 還沒追。6/13 與 8/3 記下疑似 bug:每個客戶端只有一個緩衝區,封包快速連續寫入可能蓋到還沒送出的資料,導致長度判斷錯誤;作者的測試程式用 24 bytes 負載連線正常,約 40 bytes 時好時壞;斷線後新連線進來,舊 com_id 會立刻 timeout 被殺。8/29 另注意到 kernel 5.1 之後的 io_uring 似乎比 epoll 好用。Open items: what ae_delete_time_event is really for, and the complicated recv_fn inside handle, never traced. On 6/13 and 8/3 a suspected bug was recorded: each client has one buffer, so rapid successive packets may overwrite data not yet sent and corrupt the length field; the author's test program connected reliably with 24-byte payloads but only intermittently at about 40 bytes, and after a disconnect the old com_id was killed at once by the timeout. An 8/29 aside notes that io_uring (kernel 5.1 and later) seems nicer than epoll.残った疑問:ae_delete_time_event の本当の用途、handle 内の複雑な recv_fn はまだ追えていない。6/13 と 8/3 にはバグの疑いが記録された。各クライアントのバッファは一つなので、パケットが速く連続すると未送信データを上書きし長さ判定を誤りうる。著者のテストプログラムは 24 バイトでは安定して接続できたが約 40 バイトでは不安定で、切断後は古い com_id がタイムアウトで即座に殺された。8/29 の余談では kernel 5.1 以降の io_uring は epoll より使いやすそうだと記す。

中介層與應用層:回呼註冊、命令緩衝區與 effect timeMiddleware and application layer: callbacks, the command buffer and effect timeミドルウェアとアプリケーション層:コールバック、コマンドバッファ、effect time

來源筆記:Source notes: 出典ノート:智慧交通的code.md, 致翰交接.md

應用程式經 application_registration.c 註冊:每支 app 的回呼插進 callback_list,優先權最高的在最前面。EVSP 沒有自己的號控箱控制回呼,因為它不必和雲端交換資料。雲端到 RSU(C2R)的 app section 只有 payload_len、payload、com_id 三個欄位,就是回呼的輸入;service id 就是 app id。一條執行緒 traffic_signal_packet_rx_handler 以 while(1) 讀號控箱的序列輸出,recv_info 依封包型別分派給 packet_5FCC 之類的解析函式,結果寫進全域 signal_status。這個全域同時用號誌與互斥鎖保護:號誌確保查 supermatrix 時等到最新狀態,sem_post 在狀態更新的程式裡。Applications register through application_registration.c: each app's callbacks go into callback_list, highest priority first. EVSP has no TC-box control callback because it never exchanges data with the cloud. A cloud-to-RSU (C2R) app section has just payload_len, payload and com_id and is the callback's input; the service id is the app id. A thread, traffic_signal_packet_rx_handler, loops forever reading the cabinet's serial output; recv_info dispatches by packet type to parsers such as packet_5FCC, which write into the global signal_status. That global is guarded by both a semaphore and a mutex: the semaphore makes a supermatrix lookup wait for the freshest status, and the sem_post sits in the status-updating code.アプリケーションは application_registration.c で登録され、各アプリのコールバックは優先度の高い順に callback_list へ入る。EVSP はクラウドとデータを交換しないので TC ボックス制御コールバックを持たない。クラウドから RSU へ(C2R)の app section は payload_len、payload、com_id の三つだけで、コールバックの入力になる。service id はアプリ id である。スレッド traffic_signal_packet_rx_handler は while(1) で制御器のシリアル出力を読み、recv_info がパケット種別で packet_5FCC などのパーサに振り分け、結果をグローバル signal_status に書く。このグローバルはセマフォとミューテックスの両方で守られ、セマフォは supermatrix 参照が最新状態を待つことを保証し、sem_post は状態更新コードの中にある。

命令先進命令緩衝區,附帶 cycle value:0 表示現在這個週期,1 表示下一個;若目前週期為 0 而命令寫 1,就放進 cycle 1 的緩衝區。跨週期是因為遠的路口要預先下命令。command_buf_polling 比對緩衝區與即時狀態,command_buf_send 先送 tsc_dynamic() 再送 tsc_extend(subphase, step, effect_time)。5FC5 回報的 PhaseOrder 一變就清空整個緩衝區,因為時制計畫換了,排隊的命令全部失效。廠牌差異只存在於 command_buf_send 與 tsc_extend,再往上 effect time 是唯一介面:EVSP 直接呼叫 command_buf_insert_effect_time,TSP 呼叫 command_buf_insert_adjustment 再轉成 effect time;調整量上下限要從中介層搬到應用層。Commands first enter a command buffer with a cycle value: 0 means the current cycle, 1 the next one, and if the controller is in cycle 0 and the command says 1 it goes into the cycle-1 buffer. Cross-cycle commands exist because distant intersections need the command placed in advance. command_buf_polling checks the buffer against the live status and command_buf_send issues tsc_dynamic() then tsc_extend(subphase, step, effect_time). When 5FC5 reports a changed PhaseOrder the whole buffer is cleared, because a plan change invalidates every queued command. Brand differences live only in command_buf_send and tsc_extend; above that, effect time is the single interface: EVSP calls command_buf_insert_effect_time directly, TSP calls command_buf_insert_adjustment, which converts to an effect time, and the adjustment bounds were to move from middleware into the application.コマンドはまず cycle value 付きでコマンドバッファに入る。0 は現在のサイクル、1 は次のサイクルで、制御器が cycle 0 にありコマンドが 1 なら cycle 1 のバッファに入る。サイクルをまたぐのは遠い交差点で前もってコマンドを置く必要があるからだ。command_buf_polling はバッファとリアルタイム状態を突き合わせ、command_buf_send は tsc_dynamic() の後に tsc_extend(subphase, step, effect_time) を送る。5FC5 の PhaseOrder が変わればバッファ全体をクリアする。時制計画が変われば待機中のコマンドはすべて無効だからである。メーカー差は command_buf_send と tsc_extend にしかなく、その上では effect time が唯一のインタフェースである。EVSP は command_buf_insert_effect_time を直接呼び、TSP は command_buf_insert_adjustment を呼んで effect time に変換する。調整量の上下限はミドルウェアからアプリケーション層へ移す予定だった。

effect time 的算法:difference = effect_time − adjusted_time,time = pretime + difference,上限 255。time 為負就進迴圈:tsc_dynamic()、tsc_extend(current, 1, 1)、time += pretime − 4;不能下 0,否則步階立刻結束,−4 是機器限制。例子:pretime 40、要縮短 100 秒,time = −60;−60 + 36 = −24,−24 + 36 = 12,最後 extend 到 12 等於扣 28 秒;36 + 36 + 28 = 100。The effect-time arithmetic: difference = effect_time − adjusted_time, time = pretime + difference, capped at 255. If time is negative the code loops: tsc_dynamic(), tsc_extend(current, 1, 1), time += pretime − 4; 0 cannot be sent because it ends the step at once, and the 4 is a controller limit. Example: pretime 40, shorten by 100 s, so time = −60; −60 + 36 = −24, −24 + 36 = 12, and the final extend to 12 cuts 28 s; 36 + 36 + 28 = 100.effect time の計算:difference = effect_time − adjusted_time、time = pretime + difference、上限 255。time が負ならループに入り tsc_dynamic()、tsc_extend(current, 1, 1)、time += pretime − 4 を繰り返す。0 は送れない。ステップが即座に終わるからで、−4 は制御器の制限による。例:pretime 40 で 100 秒短縮なら time = −60。−60 + 36 = −24、−24 + 36 = 12、最後に 12 へ extend して 28 秒削る。36 + 36 + 28 = 100。

typedef struct static_plan {
    uint16_t Green;         /* 5F C5 */
    uint8_t  MinGreen;      /* 5F C4 */
    uint16_t MaxGreen;
    uint8_t  Yellow;
    uint8_t  AllRed;
    uint8_t  PedGreenFlash;
    uint8_t  PedRed;
    uint16_t PreGreen;      /* Green - PedGreenFlash - PedRed: original step 1 */
} static_plan_t;

typedef struct traffic_signal_status {
    uint8_t  ControlStrategy;   /* 5F CC */
    uint8_t  SubPhaseID;
    uint8_t  StepID;
    uint16_t StepSec;
    uint8_t  PlanID;            /* 5F C8 */
    uint8_t  PhaseOrder;        /* 5F C5 */
    uint8_t  SubPhaseCount;     /* 1..8  */
    uint16_t CycleTime;
    uint16_t Offset;
    static_plan_t plan[PHASE_COUNT_MAX_NUM];
    uint8_t  control_status;    /* seems to be the app id */
} traffic_signal_status_t;

PreGreen 是 Green 減步階 2(PedGreenFlash)再減步階 3(PedRed),當時兩者都是 0,所以等於原始步階 1 的秒數。號控箱封包以 DLE、TYPE、SEQ、ADDR、LEN、ETX、CKS 包住可變長度的 INFO[];下表整理筆記中出現的型別。PreGreen is Green minus step 2 (PedGreenFlash) minus step 3 (PedRed); both were zero at the time, so it equals the original step-1 seconds. Cabinet packets wrap a variable-length INFO[] in DLE, TYPE, SEQ, ADDR, LEN, ETX and CKS bytes; the table lists the types that appear in the notes.PreGreen は Green からステップ 2(PedGreenFlash)とステップ 3(PedRed)を引いたもので、当時はどちらも 0 だったので元のステップ 1 の秒数に等しい。制御器パケットは可変長の INFO[] を DLE、TYPE、SEQ、ADDR、LEN、ETX、CKS で包む。下表はノートに現れる種別をまとめる。

封包Packetパケット 方向Direction方向 筆記中的意義Meaning as the notes describe itノートでの意味
5FCC號控箱 → RSUTC box → RSUTC ボックス → RSU即時狀態:ControlStrategy、SubPhaseID、StepID、StepSecLive status: ControlStrategy, SubPhaseID, StepID, StepSecリアルタイム状態:ControlStrategy、SubPhaseID、StepID、StepSec
5FC5號控箱 → RSUTC box → RSUTC ボックス → RSU時制計畫:PhaseOrder、SubPhaseCount(1–8)、CycleTime、Offset、各分相 Green;PhaseOrder 改變即清空命令緩衝區Timing plan: PhaseOrder, SubPhaseCount (1–8), CycleTime, Offset, each subphase's Green; a PhaseOrder change clears the command buffer時制計画:PhaseOrder、SubPhaseCount(1–8)、CycleTime、Offset、各サブフェーズの Green。PhaseOrder が変わるとコマンドバッファをクリア
5FC8號控箱 → RSUTC box → RSUTC ボックス → RSUPlanIDPlanIDPlanID
5FC4號控箱 → RSUTC box → RSUTC ボックス → RSU各分相靜態值:MinGreen、MaxGreen、Yellow、AllRed、PedGreenFlash、PedRedPer-phase static values: MinGreen, MaxGreen, Yellow, AllRed, PedGreenFlash, PedRedフェーズごとの静的値:MinGreen、MaxGreen、Yellow、AllRed、PedGreenFlash、PedRed
5F10RSU → 號控箱RSU → TC boxRSU → TC ボックス控制策略(號控 3.0 規範定義);0x15 = 21 代表 dynamic;讀回值依廠牌不同Control strategy (defined in the signal-control 3.0 spec); 0x15 = 21 means dynamic; read-back differs by brand制御戦略(信号制御 3.0 仕様で定義)。0x15 = 21 が dynamic。読み戻し値はメーカーで異なる
5F1CRSU → 號控箱RSU → TC boxRSU → TC ボックス延長:分相、步階、秒數(1–255;0 會讓步階立刻結束)Extend: subphase, step, seconds (1–255; 0 ends the step at once)延長:サブフェーズ、ステップ、秒数(1–255。0 はステップを即座に終わらせる)
5F4CRSU → 號控箱RSU → TC boxRSU → TC ボックス傳送紀錄中緊接在 EXTEND 之後的封包;筆記未解釋The packet right after EXTEND in the tx log; the notes do not gloss it送信ログで EXTEND 直後に来るパケット。ノートは説明していない

兩家號控箱廠牌的差異與時制轉換補償Vendor-specific controller behaviour and plan-change compensationメーカー固有の制御器挙動と時制転換の補償

來源筆記:Source notes: 出典ノート:智慧交通的code.md

現場有兩家廠牌(筆記的拼法本身不一致,這裡稱 A 牌與 B 牌):絕大多數是 B 牌,靠近大學校區的 2~3 個路口是 A 牌,同一廠牌還有不同韌體版本。兩家都記住剩餘秒數,但延長語意不同。A 牌相對初始值延長:步階在「剩餘秒數 + a 秒」結束,要提早結束 a 必須為負。B 牌下的是絕對時間:離步階結束的時間等於下的值減已經過時間,負值就立刻結束。B 牌自動切回 pretime,A 牌要另外下命令,這是 resume id 存在的理由,也是為何選在步階 4 送回 pretime 的命令(偵測到 step 4 就設 flag,看到 flag 就下命令並清掉)。config.txt 以 0/1 表示廠牌,改了一定要重啟程式。控制策略位元組也不同:以 5F10 下 0x15(21,dynamic),A 牌讀回 21,B 牌讀回 16;下 05 時 B 牌讀回 1,因為 B 牌不理 bit 2。關閉行人倒數的命令要下一個 phase 才生效,而且只是讓行人燈號不顯示秒數,步階仍在,箱上的監視器還在數;生效時行人紅綠燈會一起閃一下。Two brands were installed (the note spells their names inconsistently; here they are brand A and brand B). Most intersections used brand B, two or three near the university's campus used brand A, and one brand came in several firmware versions. Both remember the remaining seconds, but extension means different things. Brand A extends relative to the initial value: the step ends at remaining + a seconds, so to end early a must be negative. Brand B takes an absolute time: the time left is the commanded value minus elapsed time, and a negative result ends the step immediately. Brand B returns to pretime automatically; brand A needs a command, which is why a resume id exists and why step 4 was chosen as the moment to send the return-to-pretime command (detect step 4, set a flag; on the flag, send the command and clear it). The brand is a 0/1 value in config.txt and changing it requires a restart. The control-strategy byte differs too: sending 5F10 with 0x15 (21, dynamic) reads back 21 on brand A but 16 on brand B, and 05 reads back 1 on brand B, which ignores bit 2. The pedestrian-countdown-off command takes effect in the next phase, not the current one, and only hides the digits: the step still exists and the cabinet's monitor keeps counting; the pedestrian red and green lamps blink once together when it kicks in.現場には二つのメーカーがあった(ノートの綴りは揺れており、ここでは A 社と B 社と呼ぶ)。大半は B 社、大学キャンパス近くの 2〜3 交差点が A 社で、同じメーカーでもファームウェア版が複数ある。どちらも残り秒数を記憶するが、延長の意味が違う。A 社は初期値に対する相対で延長し、ステップは「残り秒数 + a 秒」で終わるので、早く終えるには a を負にする。B 社は絶対時間を取り、残り時間は指定値から経過時間を引いたもので、負なら即座に終了する。B 社は自動で pretime に戻るが A 社はコマンドが要り、これが resume id の存在理由であり、pretime へ戻すコマンドをステップ 4 で送ると決めた理由でもある(step 4 を検出したらフラグを立て、フラグを見たらコマンドを送って消す)。メーカーは config.txt に 0/1 で書き、変更後は必ず再起動する。制御戦略バイトも異なる。5F10 で 0x15(21、dynamic)を送ると A 社は 21、B 社は 16 を返し、05 を送ると B 社は 1 を返す。B 社はビット 2 を無視するからだ。歩行者カウントダウン停止コマンドは現在ではなく次のフェーズで効き、数字を隠すだけである。ステップは残り、制御器のモニタは数え続ける。効いた瞬間に歩行者の赤と緑が同時に一度点滅する。

時制計畫切換後的補償也不同。B 牌以週期秒數的 25 % 為原則調整,控制器自己演算加秒或減秒,正常設定下理論上四個循環內能與鄰近路口連鎖;A 牌的規則只留下一張圖。一位資深學長提出通用邏輯:保留新時制的時比比率,分兩個週期平均補償。令 C 為新時制週期、A 為補償週期、S 為時段切分點(含時差)、N 為執行新時制第 0 秒的時間點、J = N − S。J ≥ C/2 採正補償:A = C + (C − J)/2,各分相加 (C − J)/2 × 時比。J < C/2 採負補償:A = C − J/2,各分相減 J/2 × 時比。例一:舊時制週期 100、分相 70/30、時差 90;新時制 7:00 起、週期 120、分相 80/40、時差 0。到 7:00 舊週期剛跑 10 秒,跑完為 7:01:30,J = 90 ≥ 60,A = 135 秒,分相 90 與 45 秒。例二:時差 30,到 7:00 舊週期已跑 70 秒,J = 30 < 60,A = 105 秒,分相 70 與 35 秒。8/31 的交接留下疑問:兩個週期補償完真能回到連鎖嗎?等滿 120 秒才切回 pretime 是不是太慢?Compensation after a plan change differs as well. Brand B adjusts by up to 25 % of the cycle, its controller deciding whether to add or subtract seconds, so under normal settings coordination with neighbours is in theory regained within four cycles; brand A's rule survives only as a figure. A senior labmate proposed a general logic: keep the new plan's split ratios and spread the compensation evenly over two cycles. Let C be the new cycle, A the compensated cycle, S the switch point (including offset), N the moment the new plan's second 0 runs, and J = N − S. If J ≥ C/2, positive compensation: A = C + (C − J)/2 and each phase gains (C − J)/2 × its ratio. If J < C/2, negative compensation: A = C − J/2 and each phase loses J/2 × its ratio. Example 1: old plan cycle 100, phases 70/30, offset 90; new plan from 7:00, cycle 120, phases 80/40, offset 0. At 7:00 the old cycle had run 10 s and ends at 7:01:30, J = 90 ≥ 60, A = 135 s, phases 90 and 45 s. Example 2: offset 30, the old cycle had run 70 s at 7:00, J = 30 < 60, A = 105 s, phases 70 and 35 s. The 8/31 handover left two questions: do two compensated cycles really restore coordination, and is waiting a full 120 s before returning to pretime too slow?時制計画切り替え後の補償も異なる。B 社はサイクル秒数の 25 % を原則に調整し、加算か減算かは制御器が演算し、通常設定なら理論上四サイクル以内に隣接交差点と連動する。A 社の規則は図一枚しか残っていない。先輩の研究室メンバーが汎用ロジックを提案した。新時制の時比比率を保ち、二サイクルに均等に補償する。C を新時制の周期、A を補償後の周期、S を切り替え点(時差を含む)、N を新時制の第 0 秒を実行する時点、J = N − S とする。J ≥ C/2 なら正補償:A = C + (C − J)/2、各フェーズは (C − J)/2 × 時比だけ増える。J < C/2 なら負補償:A = C − J/2、各フェーズは J/2 × 時比だけ減る。例 1:旧時制は周期 100、フェーズ 70/30、時差 90。新時制は 7:00 開始、周期 120、フェーズ 80/40、時差 0。7:00 に旧サイクルは 10 秒しか進んでおらず 7:01:30 に終わる。J = 90 ≥ 60、A = 135 秒、フェーズは 90 と 45 秒。例 2:時差 30、7:00 に旧サイクルは 70 秒進んでおり、J = 30 < 60、A = 105 秒、フェーズは 70 と 35 秒。8/31 の引き継ぎでは二つの疑問が残った。二サイクルの補償で本当に連動に戻れるか、120 秒丸ごと待ってから pretime に戻すのは遅すぎないか。

作者實作的功能(2021 年 5 月到 8 月)Features the author implemented (May to August 2021)著者が実装した機能(2021 年 5 月〜8 月)

來源筆記:Source notes: 出典ノート:智慧交通的code.md, 致翰交接.md

  • TSP/EVSP 開關:TSP_on_cloud_packet_rx 處理 TSP 收到雲端封包後的動作,另設計 EVSP_on_cloud_packet_rx。disable 只是讓 IPC 不送命令到號控箱,命令仍塞進緩衝區;enable 時清空緩衝區。開關是輸入參數而非改 binary。TSP/EVSP on and off: TSP_on_cloud_packet_rx handles TSP's reaction to a cloud packet and an EVSP_on_cloud_packet_rx was designed alongside. Disable only stops the IPC sending commands to the cabinet while commands still enter the buffer; enable clears the buffer. The switch is an input parameter, not a binary change.TSP/EVSP のオン・オフ:TSP_on_cloud_packet_rx が TSP のクラウドパケット受信後の処理を担い、並行して EVSP_on_cloud_packet_rx を設計した。disable は IPC から制御器へのコマンド送信を止めるだけでコマンドはバッファに入り続け、enable はバッファをクリアする。スイッチはバイナリ変更ではなく入力パラメータである。
  • 行人倒數開關:會議定調屬於 TSP service,實作在 TSP_on_cloud_packet_rx;廠牌用 0/1 全域變數區分。Pedestrian countdown on/off: ruled a TSP service in the meeting and implemented in TSP_on_cloud_packet_rx; the brand is a 0/1 global.歩行者カウントダウンのオン・オフ:会議で TSP サービスと決まり TSP_on_cloud_packet_rx に実装した。メーカーは 0/1 のグローバル変数で区別する。
  • EVSP OBU 封包轉傳雲端:不在回呼裡做,而是在 OBU_packet_rx_event_handler 一偵測到 service id 1 就先轉傳再呼叫回呼,因為回呼拿到的變數已太複雜;作者自問是否符合架構。封包長 85 bytes(不是 86,刪了一個 byte),common field 放 RSU 資訊,specific field 放從 OBU 封包撈出的 EVSP 資訊。6/4 把轉傳從中介層搬進 EVSP service。Forwarding EVSP OBU packets to the cloud: done not in the callback but in OBU_packet_rx_event_handler, forwarding as soon as service id 1 is seen and calling the callback afterwards, because the callback's variables were already too tangled; the note asks whether this fits the architecture. The packet is 85 bytes (not 86, one byte was dropped), the common field carries RSU information and the specific field the EVSP data pulled from the OBU packet. On 6/4 the forwarding moved from the middleware into the EVSP service.EVSP OBU パケットのクラウド転送:コールバック内ではなく OBU_packet_rx_event_handler で service id 1 を見た時点で転送し、その後コールバックを呼ぶ。コールバックの変数が既に複雑すぎたためで、ノートはこれがアーキテクチャに合うか自問している。パケットは 85 バイト(86 ではない、1 バイト削除)、common field に RSU 情報、specific field に OBU パケットから抜いた EVSP 情報を載せる。6/4 に転送はミドルウェアから EVSP サービスへ移した。
  • 重啟 daemon 與 OTA:收到雲端特定封包就 kill 自己、由 daemon 重啟讓新 config 生效;IPC 重啟後的網路問題改用一支 script 設定路由表再啟動中介層,並到全部路口裝 ifmetric;7/26 補讀 systemd 與 WantedBy=multi-user.target。Restart daemon and OTA: on a specific cloud packet the program kills itself and the daemon restarts it so a new config takes effect; the post-reboot network problem became a script that sets the route table before starting the middleware, plus ifmetric on every intersection; on 7/26 the author read up on systemd and WantedBy=multi-user.target.再起動デーモンと OTA:特定のクラウドパケットでプログラムが自身を kill し、デーモンが再起動して新設定を反映する。IPC 再起動後のネットワーク問題は、ルートテーブルを設定してからミドルウェアを起動するスクリプトと全交差点への ifmetric 導入で解決した。7/26 には systemd と WantedBy=multi-user.target を読んだ。
  • 設定外部化:EVSP 負責人列出要拉出的 EVSP_HOST_OBU_PACKET_TIMEOUT 20、EVSP_HOST_OBU_LIST_TIMEOUT 120(原寫死在 EVSP_timer_event.h)、MAX_GREEN 120;TSP 預計拉出 TSP_REMAINING_DISTANCE_MAX 500 與 TSP_HOST_OBU_LIST_TIMEOUT 120。系統設定含延長量限制(%)、縮短量限制(%)與延長限制開關。中介層與 EVSP 各有 config.txt,驗收前折衷放一起。Config externalisation: the EVSP owner listed EVSP_HOST_OBU_PACKET_TIMEOUT 20 and EVSP_HOST_OBU_LIST_TIMEOUT 120 (hard-coded in EVSP_timer_event.h) and MAX_GREEN 120; TSP was to expose TSP_REMAINING_DISTANCE_MAX 500 and TSP_HOST_OBU_LIST_TIMEOUT 120. The system config holds the extension limit (%), shortening limit (%) and an extension-limit switch. Middleware and EVSP each have a config.txt, kept together as a compromise until acceptance.設定の外部化:EVSP 担当者が EVSP_HOST_OBU_PACKET_TIMEOUT 20、EVSP_HOST_OBU_LIST_TIMEOUT 120(EVSP_timer_event.h にハードコード)、MAX_GREEN 120 を列挙した。TSP は TSP_REMAINING_DISTANCE_MAX 500 と TSP_HOST_OBU_LIST_TIMEOUT 120 を切り出す予定。システム設定には延長上限(%)、短縮上限(%)、延長上限スイッチが入る。ミドルウェアと EVSP はそれぞれ config.txt を持ち、検収までは妥協して同居させた。
  • 錯誤回報與 NAK:錯誤以 bitmap 回報,timeout 時把 TC 的 error bit 與 16 位元一起 OR。送往號控箱的封包有遞增的 SEQ,所以建一個 255 格的重送緩衝區,每送一包存一份,收到對應 NAK 就重送;連續五次失敗視為系統掛掉(次數規格書有寫)。Error report and NAK: errors are a bitmap, and on timeout the TC error bit is ORed into the 16-bit word. Packets to the cabinet carry an incrementing SEQ, so a 255-slot retransmit buffer keeps a copy of each packet and resends on the matching NAK; five failures count as a dead system (the count is in the spec).エラー報告と NAK:エラーはビットマップで、タイムアウト時は TC のエラービットを 16 ビット語に OR する。制御器宛パケットには増加する SEQ があるので、255 スロットの再送バッファに各パケットのコピーを保持し、対応する NAK で再送する。五回失敗すればシステム停止とみなす(回数は仕様書にある)。
  • 其他:log 加色碼(綠色 \e[1;4;32m)並定期清理,/var 與 .local 很吃容量;NTP 改用本案內部伺服器,21 台 RSU 設定完成。5/31 一次「EXTEND 送了卻沒生效」的紀錄,原因只是檔案沒複製過去,make 也沒檢查出來。Other: colour codes in the log (green is \e[1;4;32m) and periodic cleanup, since /var and .local eat disk; NTP moved to the project's internal server and was set up on 21 RSUs. A 5/31 record where EXTEND was sent but nothing happened turned out to be a file not copied over, which make did not catch.その他:ログにカラーコード(緑は \e[1;4;32m)を入れ定期的に掃除する。/var と .local がディスクを食うからだ。NTP は案件内部のサーバに移し 21 台の RSU で設定を終えた。5/31 の「EXTEND を送ったのに何も起きない」記録は、ファイルがコピーされておらず make も検出しなかっただけだった。

6/24 的筆記把同一句話連寫三次:安裝道路側時,預設一定要關掉 EVSP 和 TSP,不然會出事。命令緩衝區在服務啟動時清空,disable 時不清;host OBU 清單為空時切回 pretime。The 6/24 note repeats one sentence three times: when installing on the roadside, EVSP and TSP must default to OFF, or something will go wrong. The command buffer is cleared when a service is enabled, not when it is disabled; when the host OBU list is empty, switch back to pretime.6/24 のノートは同じ一文を三回繰り返す。路側に設置するとき、EVSP と TSP は必ずデフォルトで OFF にすること。さもないと事故が起きる。コマンドバッファはサービス有効化時にクリアし、無効化時はクリアしない。host OBU リストが空なら pretime に戻す。

現場工作:檢核表、連線調查、路測與雲端紀錄Field work: checklist, reachability survey, road tests and the cloud log現場作業:チェックリスト、到達性調査、路上試験、クラウドログ

來源筆記:Source notes: 出典ノート:rsu checklist.md, 智慧交通的code.md

rsu checklist.md 是路口實驗的前後檢核表。實驗前:資料庫中的 RSU id 與位址正確;in-service flag 開啟;RSU config 的 RSU id 正確;config 的 GPS 位置正確(影響 TSP 二階能否作動);log 顯示 EVSP/TSP 已 enable;supermatrix 檔名的 plan 與現行 plan 一致;EVSP 觸控點檔名的 plan 一致;用 vim 或 cat 檢查觸控點檔案格式。實驗後:關掉 TSP/EVSP;恢復行人倒數。附註記下中介層與 EVSP 的 config.txt 分別在專案的 config/ 與 application/EVSP/config/。rsu checklist.md is the before-and-after list for intersection experiments. Before: the RSU id and address in the database are correct; the in-service flag is on; the RSU id in the RSU config is correct; the GPS position in the config is correct (it decides whether TSP stage 2 acts); the log shows EVSP/TSP enabled; the plan in the supermatrix file name matches the current plan; the plan in the EVSP touch-point file name matches; the touch-point file format checks out under vim or cat. After: turn TSP/EVSP off; restore the pedestrian countdown. A footnote places the middleware and EVSP config.txt files under config/ and application/EVSP/config/ in the project tree.rsu checklist.md は交差点実験の前後チェックリストである。実験前:データベースの RSU id とアドレスが正しい、in-service フラグが有効、RSU 設定の RSU id が正しい、設定の GPS 位置が正しい(TSP 第二段階が動くかを左右する)、ログで EVSP/TSP が有効、supermatrix ファイル名の plan が現行 plan と一致、EVSP タッチポイントファイル名の plan も一致、タッチポイントファイルの書式を vim か cat で確認。実験後:TSP/EVSP を切る、歩行者カウントダウンを戻す。脚注はミドルウェアと EVSP の config.txt がプロジェクトの config/ と application/EVSP/config/ にあると記す。

連線調查:5/18 之後的 SSH 掃描列出 13 個 ping 得到卻 SSH 不進去的路口;5/27 補查三個:中華路/大橋一街能 SSH 但 DSRC 因網路線壞掉連不上,開元路/開元路 485 巷與開元路/林森路三段的 ORing 路由器 SSH 埠一直沒開,可能是 IPC 設定。六月底中華路與中山南路沿線 9 個路口已正常和雲端溝通並自動刪 log,資料庫列了 23 台 RSU。連 RSU 要兩層 SSH:先到 IPC,再到 DSRC 盒子。路測紀錄零散但具體:6/9 GPS 資料錯誤是 write_float 誤用成 write_uint32_t;公車本來就在 special OBU list 歸 TSP 管,型別 0 的一般車輛才進 normal OBU list;resume 是為了強制回到 pretime。6/11 用假 GPS 測 EVSP「切斷並延長 target phase」。7/6 的錯誤:號控箱 timeout、invalid OBU packet(疑似距離)、切到手動再切回來後動態回報消失。7/9 一台 RSU 回報 2000 TC status 異常,另一台 sem_timedwait: Connection timed out。7/21 把中山南路與開元路上六個路口更新到當日軟體;其中一個下太多指令會當機,另一個下行人倒數指令會當掉。8/6 列出硬體有狀況的機器:兩台號控箱、一台 DSRC;另一台 RSU 一直斷線,懷疑是 DoS。Reachability: an SSH sweep after 5/18 listed 13 intersections that answered ping but refused SSH; a 5/27 follow-up checked three more: Zhonghua Rd / Daqiao 1st St could be reached but its DSRC box was cut off by a broken cable, and at Kaiyuan Rd / Lane 485 and Kaiyuan Rd / Linsen Rd Sec. 3 the ORing router's SSH port never opened, possibly an IPC setting. By late June nine intersections along Zhonghua Rd and Zhongshan S. Rd were talking to the cloud normally and auto-deleting logs, and the database listed 23 RSUs. Reaching an RSU takes two SSH hops, into the IPC and then into the DSRC box. The road-test entries are scattered but concrete: on 6/9 the GPS data was wrong because write_float had been used as write_uint32_t; buses were already in the special OBU list under TSP, and only type-0 ordinary vehicles go into the normal OBU list; resume exists to force a return to pretime. 6/11 tested EVSP's "cut and extend the target phase" with fake GPS. Errors on 7/6: cabinet timeouts, invalid OBU packets (probably distance), and the dynamic report vanishing after switching to manual and back. On 7/9 one RSU reported a 2000 TC-status fault and another sem_timedwait: Connection timed out. On 7/21 six intersections on Zhongshan S. Rd and Kaiyuan Rd got that day's software; one crashes when too many commands are sent, another hangs on the pedestrian-countdown command. 8/6 lists the hardware-fault machines: two cabinets and one DSRC box; another RSU kept disconnecting, DoS suspected.到達性:5/18 以降の SSH 走査では ping に応答するが SSH に入れない交差点が 13 か所あった。5/27 の追加調査では三か所を確認し、中華路/大橋一街は SSH できるがケーブル破損で DSRC ボックスに届かず、開元路/開元路 485 巷と開元路/林森路三段は ORing ルータの SSH ポートが開かず、IPC 設定の問題かもしれなかった。6 月末には中華路と中山南路沿いの 9 交差点がクラウドと正常に通信しログを自動削除しており、データベースには 23 台の RSU が載っていた。RSU に入るには IPC へ、次に DSRC ボックスへと二段の SSH が要る。路上試験の記録は断片的だが具体的だ。6/9 の GPS データの誤りは write_float を write_uint32_t として使っていたため。バスは元々 TSP 管轄の special OBU list にあり、type 0 の一般車両だけが normal OBU list に入る。resume は pretime へ強制的に戻すためにある。6/11 は偽 GPS で EVSP の「target phase を切って延長する」を試験した。7/6 のエラー:制御器のタイムアウト、invalid OBU packet(距離が原因らしい)、手動に切り替えて戻すと動的報告が消える。7/9 にはある RSU が 2000 TC status の異常を報告し、別の RSU で sem_timedwait: Connection timed out。7/21 には中山南路と開元路の六交差点を当日版ソフトに更新した。うち一か所はコマンドを送りすぎるとクラッシュし、別の一か所は歩行者カウントダウンコマンドでハングする。8/6 はハードウェア不良機を列挙する。制御器二台と DSRC 一台。別の RSU は切断を繰り返し DoS が疑われた。

EVSP 多車情境依 EVSP 負責人的分析整理。同一 target phase:ev1 未離開、ev2 進入,依序離開則兩車都能通過;若 ev2 超車先離開,離開時要檢查是否還有同 target phase 的車,有就不取消延長;ev1 已離開、ev2 才進入則不延長,免得另一方向永遠等不到它的 phase。不同 target phase:ev1 未離開時 ev2 先離開不可能(除非闖紅燈);後車晚離開時各自縮短的都是自己的 target phase,反而幫到對方;ev1 已離開、ev2 才進入時,ev1 已切回 pretime,但因為用 resume id,可被 ev2 的命令取代。排程原則是先到先服務。EVSP multi-vehicle scenarios follow the EVSP owner's analysis. Same target phase: if ev2 enters before ev1 leaves and they leave in order, both get through; if ev2 overtakes and leaves first, check on its departure whether another same-phase vehicle remains and if so do not cancel the extension; if ev1 has already left when ev2 enters, do not extend, or the other direction never gets its phase. Different target phases: with ev1 still inside, ev2 cannot leave first (unless it runs the red); if the rear car leaves later, each shortens only its own target phase, which actually helps the other; if ev1 has left when ev2 enters, ev1 has switched back to pretime, but since it used the resume id, ev2's command can replace it. Scheduling is first come, first served.EVSP の複数車両シナリオは EVSP 担当者の分析に従う。同じ target phase:ev1 が去る前に ev2 が入り順番どおり去れば両車とも通過できる。ev2 が追い越して先に去るなら、離脱時に同じフェーズの車が残っているか確認し、残っていれば延長を取り消さない。ev2 が入った時点で ev1 が去っていれば延長しない。さもないと反対方向が永遠にフェーズを得られない。異なる target phase:ev1 がまだ中にいるとき ev2 が先に去ることはない(赤信号無視を除く)。後続車が後から去るなら各自の target phase だけを短縮するので、むしろ相手を助ける。ev2 が入った時点で ev1 が去っていれば ev1 は pretime に戻しているが、resume id を使っているので ev2 のコマンドで置き換えられる。スケジューリングは先着順である。

8/11 的雲端 log 值得解讀:msgRecvRSUAck() 收到某台 RSU 的 98 bytes 封包,含 deviceType 1、RSU 的 GPS、serviceFlag 2、controlCmdFlag 1、controlTypeFlag 0,命令 id 3002 回報 Success、hwStatus 0。接著 msgRecvRSUPlan() 解出 curSubPhaseID 2、curStepID 1、remindSec 21、planID 7、cycleTime 120、offset 0、subPhaseCount 4,四個分相 green 10/47/18/25、yellow 皆 3、allRed 0/3/2/3、pedGreenFlash 與 pedRed 皆 0、maxGreen 100、minGreen 2/5/5/5。綠黃全紅加總正好是 120 秒的週期。The 8/11 cloud log is worth decoding: msgRecvRSUAck() received a 98-byte packet from one RSU with deviceType 1, the RSU's GPS, serviceFlag 2, controlCmdFlag 1 and controlTypeFlag 0; command id 3002 returned Success with hwStatus 0. The following msgRecvRSUPlan() decoded curSubPhaseID 2, curStepID 1, remindSec 21, planID 7, cycleTime 120, offset 0, subPhaseCount 4, with four subphases of green 10/47/18/25, yellow 3 each, allRed 0/3/2/3, pedGreenFlash and pedRed 0, maxGreen 100, minGreen 2/5/5/5. Green plus yellow plus all-red adds up exactly to the 120 s cycle.8/11 のクラウドログは解読する価値がある。msgRecvRSUAck() がある RSU から 98 バイトのパケットを受け、deviceType 1、RSU の GPS、serviceFlag 2、controlCmdFlag 1、controlTypeFlag 0 を含み、コマンド id 3002 は Success、hwStatus 0 で返った。続く msgRecvRSUPlan() は curSubPhaseID 2、curStepID 1、remindSec 21、planID 7、cycleTime 120、offset 0、subPhaseCount 4 を解読し、四つのサブフェーズは green 10/47/18/25、yellow 各 3、allRed 0/3/2/3、pedGreenFlash と pedRed 0、maxGreen 100、minGreen 2/5/5/5 だった。緑・黄・全赤の合計はちょうど 120 秒の周期になる。

交接:離職同事的紀錄、實驗室會議與交接文件寫法Handover: the departing colleague's note, lab meetings and how to write a handover引き継ぎ:退職する同僚の記録、研究室会議、引き継ぎ文書の書き方

來源筆記:Source notes: 出典ノート:致翰交接.md, 交接文件格式.md, 智慧運輸.md, 智慧交通的code.md

致翰交接.md 記下中介層同事離開前交代的事:RSU 還沒收 DSRC 的錯誤封包,但 DSRC 端已完成;callback_list 對不同 event 的執行順序都不一樣;dispatcher 的 device id 0 就是 DSRC 封包;每一台車就是一個 OBU 物件。同篇記了 5/11 的實驗室會議:沙崙要再裝兩個路口,由合作廠商出資;通訊夥伴要向交通部簡報,含 SAE 標準;雲端關閉行人倒數的 C2R 封包保留 type 是否還有意義;OTA 的 target phase 要不要和 plan id 掛勾(公車靠雲端更新,緊急車輛沒雲端只能靠設定檔);緊急車輛的 timeout 寫死在 binary,應用層設定應與中介層分開以利 OTA,驗收前折衷放一起;最晚 5/26 測試。致翰交接.md records what the middleware colleague passed on before leaving: the RSU does not yet receive DSRC error packets, though the DSRC side is done; callback_list runs in a different order for each event; dispatcher device id 0 means a DSRC packet; one vehicle is one OBU object. The same note holds the 5/11 lab meeting: two more intersections at Shalun, paid for by a partner company; the telecom partner would brief the Ministry of Transportation, SAE standards included; whether keeping the packet type of the cloud's pedestrian-countdown-off C2R packet still means anything; whether the OTA target phase should be tied to the plan id (buses update via the cloud, emergency vehicles have no cloud and rely on config files); the emergency-vehicle timeout sits in the binary, so application config should be separated from middleware config for OTA, kept together until acceptance; testing by 5/26.致翰交接.md はミドルウェア担当の同僚が退職前に伝えた事項を記す。RSU はまだ DSRC のエラーパケットを受け取っていないが DSRC 側は完成。callback_list の実行順はイベントごとに異なる。dispatcher の device id 0 は DSRC パケット。一台の車両が一つの OBU オブジェクト。同じノートに 5/11 の研究室会議もある。沙崙にさらに二交差点を協力企業の費用で設置する。通信パートナーが交通部に SAE 規格を含めて説明する。クラウドの歩行者カウントダウン停止 C2R パケットの type を残す意味があるか。OTA の target phase を plan id に結び付けるか(バスはクラウド経由で更新、緊急車両はクラウドがなく設定ファイル頼み)。緊急車両のタイムアウトはバイナリに埋まっており、OTA のためアプリ設定をミドルウェア設定から分離すべきだが検収までは同居。遅くとも 5/26 に試験。

智慧運輸.md 的會議紀錄還有:9/21 的分工問題(RSU 端的 4G 誰負責、RSU 定期向雲端回報誰負責、乙太網路正常但 RSU 故障時要丟錯誤碼給 IPC、沒測過 EVSP 與 TSP 同時存在、十月中下旬到測試園區路測);9/28 的手機不耐高溫問題,選項是藏起手機 UI、或改用廠商 OBU 拿掉加減速提示與剩餘秒數,AP 路由器也要耐高溫;另有八個路口沒有網路或用別家電信;9/30 與通訊層同學討論錯誤碼定義;10/13 問 oslink 請求太多會不會爆掉(10 Hz 還是 100 Hz);12/1 EVSP 與 TSP 都用測試碼測完,OTA 和加密未做,error report 的 bit 對應錯誤訊息,雲端斷線行為要寫成文件,短暫斷線與長時間斷線分開處理。交接文件格式.md 只有三個連結,都是「如何寫好交接文件」的中文文章(Medium、iThome,以及作者註記「比較接近」的 kknews)。作者自己也在準備交接:8/31 列了 RSU 故障排除 SOP(判斷硬體或軟體)、號控箱廠商的維護 SOP、給電信業者的操作手冊與故障排除教育訓練(不在與交通局的合約內)。The meeting record in 智慧運輸.md also holds: the 9/21 ownership questions (who owns 4G on the RSU, who owns the periodic RSU report to the cloud, send an error code to the IPC when Ethernet is fine but the RSU is faulty, EVSP and TSP never tested together, road tests at the test campus in mid-to-late October); the 9/28 problem that phones cannot stand the heat, with the options of hiding the phone UI or using the vendor OBU with acceleration hints and remaining seconds removed, plus a heat-tolerant AP router; eight intersections had no network or another carrier's; 9/30 defined error codes with the com-layer owner; 10/13 asked whether oslink collapses under too many requests (10 Hz or 100 Hz); on 12/1 EVSP and TSP had passed the test code, OTA and encryption were missing, error-report bits map to messages, cloud-disconnect behaviour had to be documented, and short reconnects and long outages handled separately. 交接文件格式.md is just three links, all Chinese articles on writing a good handover document (Medium, iThome, and a kknews piece the author marked as closest). The author was preparing a handover too: 8/31 lists an RSU troubleshooting SOP (hardware or software), a maintenance SOP for the cabinet vendor, and an operations manual plus troubleshooting training for the telecom contractor (outside the contract with the Transportation Bureau).智慧運輸.md の会議記録にはさらに次がある。9/21 の担当問題(RSU 側の 4G は誰が担当するか、RSU からクラウドへの定期報告は誰か、イーサネットは正常だが RSU が故障したとき IPC にエラーコードを送る、EVSP と TSP の同時稼働は未試験、10 月中旬から下旬に試験キャンパスで路上試験)。9/28 のスマートフォンが高温に耐えない問題では、UI を隠す案、ベンダ OBU に替えて加減速ヒントと残り秒数を外す案があり、AP ルータも耐熱にする。八交差点にはネットワークがないか別の通信事業者だった。9/30 は通信層担当者とエラーコードの定義を議論。10/13 は oslink がリクエスト過多で落ちるか(10 Hz か 100 Hz か)。12/1 には EVSP と TSP ともテストコードで試験済み、OTA と暗号化は未着手、エラー報告のビットはメッセージに対応、クラウド切断時の挙動を文書化、短い再接続と長時間の断を分けて扱う。交接文件格式.md はリンク三本だけで、いずれも「良い引き継ぎ文書の書き方」の中国語記事(Medium、iThome、著者が「一番近い」と注記した kknews)。著者自身も引き継ぎを準備していた。8/31 には RSU 障害対応 SOP(ハードウェアかソフトウェアか)、制御器ベンダの保守 SOP、通信事業者向けの操作マニュアルと障害対応研修(交通局との契約外)が列挙されている。

未解的問題與可帶走的教訓Open questions and lessons未解決の問題と教訓

來源筆記:Source notes: 出典ノート:智慧交通的code.md, 智慧運輸.md

作者在「不解的問題」直接列出兩題:effect time 與 adjusted time 到底是什麼關係;create timer API 的用法與目的尚未掌握。散落各處的問號還有:subphase id、step id 與 plan id 的關係;control_status 的意義;report_plan() 裡 dynamic plan 與 static plan 的差別;取消某觸控點的控制後再碰到同路口其他觸控點,RSU 會怎樣(公車也許還好,EVSP 呢);切成手動時命令只排在緩衝區該怎麼處理;重啟前要不要先對號控箱下復位指令;RSU 會不會收到另一台 RSU 的封包;com 初始化時雲端若從未連入,送往雲端的封包會從 DSRC 廣播出去。Under "unresolved questions" the author lists two outright: what the relationship between effect time and adjusted time really is, and what the create-timer API is for and how to use it. Question marks elsewhere add: how subphase id, step id and plan id relate; what control_status means; the difference between dynamic and static plan in report_plan(); what the RSU does when control at one touch point is cancelled and another touch point of the same intersection is hit later (perhaps fine for buses, but EVSP?); what to do in manual mode when commands merely queue in the buffer; whether a reset command should go to the cabinet before a restart; whether an RSU can receive another RSU's packet; and that at com init, if the cloud has never connected, cloud-bound packets go out as DSRC broadcasts.「未解決の問題」で著者は二つを明記する。effect time と adjusted time の関係は何なのか、create timer API の使い方と目的をまだ把握していない。各所の疑問符はさらに続く。subphase id、step id、plan id の関係、control_status の意味、report_plan() の dynamic plan と static plan の違い、あるタッチポイントの制御を取り消した後に同じ交差点の別のタッチポイントに当たったら RSU はどうなるか(バスはまだしも EVSP は)、手動モードでコマンドがバッファに溜まるだけのときどう扱うか、再起動前に制御器へリセットコマンドを送るべきか、RSU が別の RSU のパケットを受け取ることがあるか、com 初期化時にクラウドが一度も接続していないとクラウド宛パケットが DSRC ブロードキャストとして出ること。

可帶走的教訓:硬體廠牌差異壓在最底層的一兩支函式裡,上層只認一個介面(effect time);任何會動到路口號誌的功能,安裝時預設必須關閉;改 config 後要重啟,make 不會幫你檢查漏掉的檔案;現場實驗前後各一份檢核表,比記憶可靠;交接要寫下「哪些還沒做」和「哪些決定是折衷」,不只是程式怎麼跑。Lessons: push hardware-brand differences down into one or two bottom-level functions and let everything above speak a single interface (effect time); any feature that can touch a live signal must default to off at installation; restart after changing config, and do not expect make to notice a file you forgot to copy; a written checklist before and after each field test beats memory; and a handover should record what is not yet done and which decisions were compromises, not only how the code runs.教訓:ハードウェアメーカーの差は最下層の一つ二つの関数に押し込め、上層は単一のインタフェース(effect time)だけを使う。実際の信号に触れうる機能は設置時にデフォルトでオフにする。設定を変えたら再起動し、コピーし忘れたファイルを make が見つけると期待しない。現場試験の前後に書かれたチェックリストは記憶より信頼できる。引き継ぎにはコードの動き方だけでなく「まだ終わっていないこと」と「どの決定が妥協だったか」を書く。

值得保留的公開參考:OSlink 的 GitHub 倉庫是 DSRC 盒子上跑的程式;一位同學關於 TSP 進入 EVSP 後再回到 TSP 的論文發表在 MDPI Sensors 2020, 20(2), 508。筆記裡的 Google Drive、OneDrive、HackMD 連結與所有登入憑證皆刻意未收錄。Public references worth keeping: the OSlink GitHub repository is the program on the DSRC box, and a labmate's paper on TSP entering EVSP and returning to TSP appeared in MDPI Sensors 2020, 20(2), 508. The Google Drive, OneDrive and HackMD links and every credential in the notes are deliberately left out.残す価値のある公開参考資料:OSlink の GitHub リポジトリは DSRC ボックスで動くプログラムで、TSP から EVSP に入り再び TSP に戻る研究室メンバーの論文は MDPI Sensors 2020, 20(2), 508 に掲載された。ノート内の Google Drive、OneDrive、HackMD のリンクと認証情報はすべて意図的に除外した。

回到頂端 ↑Back to top ↑ページ上部へ ↑

計算機結構、記憶體階層與並行原語Computer architecture, memory hierarchy and concurrency primitives計算機アーキテクチャ、メモリ階層と並行処理プリミティブ

九篇筆記屬於作者的資格考準備與伴隨的閱讀:多核心仰賴的快取一致性協定、由此而來的 DMA 陷阱、管線、IEEE 754、號誌與 RCU、一篇 runahead 執行的論文,以及檔案系統工作需要的兩種樹。大多數筆記很短、以問號結尾;本節說明各篇記錄了什麼,並列出未解問題。Nine notes belong to the author's qualifying-exam preparation and the reading around it: the cache-coherence protocol every multicore relies on, the DMA pitfalls that follow from it, pipelining, IEEE 754, semaphores and RCU, a paper on runahead execution, and the two trees needed for file-system work. Most are short and end in question marks; this section says what each records and lists the open questions.九つのノートは著者の資格試験の準備とそれに伴う読書に属する。マルチコアが依存するキャッシュ一貫性プロトコル、そこから生じる DMA の落とし穴、パイプライン、IEEE 754、セマフォと RCU、runahead 実行の論文、そしてファイルシステムの作業で必要な二つの木である。ほとんどは短く疑問符で終わる。この節では各ノートの記録内容を述べ、未解決の問いを列挙する。

MESI 與 MSI:快取一致性協定MESI and MSI: cache-coherence protocolsMESI と MSI:キャッシュ一貫性プロトコル

來源筆記:Source notes: 出典ノート:mesi protocol(也稱為伊利諾斯協議,是因為該協議由伊利諾斯州立大學提出).md

筆記以協定的別名「伊利諾協定」開場(以提出者所在的伊利諾大學命名)。每條快取行多帶兩個位元編碼四種狀態,作者用自己的話改寫:M 是本處理器持有最新資料且與記憶體不同;E 是本處理器持有最新資料但與記憶體相同;S 與 I 只留下空白標題。兩種匯流排交易:BusRdX 是另一顆處理器發生寫入失誤、想寫入自己沒有的區塊並從某處取得資料時聽到的訊號(「從哪裡」加了問號);BusUpgr 是另一顆處理器寫入它已以共享狀態持有的區塊、只需升級權限時聽到的訊號。寫入策略依作者的理解:write-back 沒有真的寫回記憶體,只是告訴其他快取已經寫了,稍後才寫回;write-through 每次儲存都真的寫入記憶體。The note opens with the protocol's nickname, the Illinois protocol (after the University of Illinois where it was proposed). Each cache line carries two extra bits encoding four states, which the author paraphrased: M means this processor holds the newest copy and it differs from memory; E means this processor holds the newest copy and it matches memory; S and I were left as empty headings. Two bus transactions: BusRdX is heard when another processor takes a write miss, wants a block it does not hold and fetches it from somewhere ("from where" got a question mark); BusUpgr is heard when another processor writes a block it already holds in the shared state and only needs to upgrade its permission. The write policies as the author understood them: write-back does not really write memory, it only tells the other caches the write happened and writes memory later; write-through really writes memory on every store.ノートはプロトコルの別名「イリノイ・プロトコル」から始まる(提案したイリノイ大学にちなむ)。各キャッシュラインは追加の 2 ビットで四つの状態を符号化し、著者は自分の言葉で言い換えた。M は本プロセッサが最新のデータを持ちメモリと異なる、E は最新のデータを持ちメモリと同じ、S と I は見出しだけが空のまま。二つのバストランザクション。BusRdX は別のプロセッサが書き込みミスを起こし、持っていないブロックをどこかから取得するときに聞こえる(「どこから」に疑問符)。BusUpgr は別のプロセッサが共有状態で既に持つブロックに書き込み、権限の昇格だけが必要なときに聞こえる。書き込み方式は著者の理解で、write-back は実際にはメモリに書かず、他のキャッシュに書いたと伝えて後で書き戻す。write-through は各ストアごとに本当にメモリへ書く。

筆記抄下一張中文解說的觸發事件表,隨即懷疑「遠端讀取:其他 cache 讀取本地 cache 資料」的措辭,應指其他快取讀寫的資料本地也有一份。修正後的表格如下,第三欄補上對本地快取行的影響。The note copies a trigger-event table from a Chinese explainer and at once doubts the wording "remote read: another cache reads local cache data", which should mean another cache reads or writes data the local cache also holds. The corrected table is below, with a third column for the effect on the local line.ノートは中国語の解説からトリガーイベント表を写し、すぐに「リモート読み取り:他のキャッシュがローカルキャッシュのデータを読む」という表現を疑っている。他のキャッシュが読み書きするデータをローカルも持つ、という意味のはずだ。修正後の表を以下に示し、三列目にローカルラインへの影響を補った。

觸發事件Trigger eventトリガーイベント 意義Meaning意味 本地快取行的變化Effect on the local lineローカルラインの変化
本地讀取(Local read)Local readローカル読み取り(Local read) 本地快取讀取自己持有的資料The local cache reads its own copyローカルキャッシュが自分の持つデータを読む M、E、S 不變;I 失誤後重新讀取,落在 E 或 SM, E, S stay; I misses, refetches, lands in E or SM、E、S はそのまま。I はミスして再読み込みし、E か S になる
本地寫入(Local write)Local writeローカル書き込み(Local write) 本地快取寫入自己持有的資料The local cache writes its own copyローカルキャッシュが自分の持つデータに書く M 不變;E 不發訊號直接變 M;S 發 BusUpgr 後變 M;I 發 BusRdX 後變 MM stays; E becomes M silently; S sends BusUpgr then M; I sends BusRdX then MM はそのまま。E は信号なしで M に。S は BusUpgr を出して M に。I は BusRdX を出して M に
遠端讀取(Remote read)Remote readリモート読み取り(Remote read) 其他快取讀取本地也持有的區塊Another cache reads a block this cache also holds他のキャッシュが、ローカルも持つブロックを読む M 先 flush 再降為 S;E 降為 S;S 維持 SM flushes and drops to S; E drops to S; S stays SM は flush してから S に。E は S に。S は S のまま
遠端寫入(Remote write)Remote writeリモート書き込み(Remote write) 其他快取寫入本地也持有的區塊Another cache writes a block this cache also holds他のキャッシュが、ローカルも持つブロックに書く M 先 flush 再變 I;E 與 S 直接變 IM flushes and becomes I; E and S go straight to IM は flush してから I に。E と S はそのまま I に

三張狀態圖貼自兩個來源,引出作者最尖銳的問題:一張圖的 S→S 自迴圈有兩個事件,另一張只有一個。作者判斷最正確的 MIT 版本證實 S→S 確有兩種情況:本地讀取命中,以及其他快取對本快取也共享的區塊發出 BusRd。筆記也記了一條不確定的規則:聽到 BusRdX 或 flush 時,M、E、S 的行要趕快標為無效。最長的一段談狀態的精確性:M 與 E 永遠精確,S 可能過時。若某快取作廢了一條 S 的行,另一個快取實際上可能已獨享,卻不會升級為 E,因為快取不廣播作廢,也沒有人保存副本數量。寫入路徑:寫 S 的行先作廢其他共享者(筆記寫成「本地改 E、其他改 I」)再寫入進 M;寫 I 的行先經快取控制器重讀、落在 E 或 S,再寫入進 M。所以 read-modify-write 需要兩次匯流排請求,除非已在 E。Three state diagrams pasted from two sources raised the author's sharpest question: one diagram's S to S self-loop carries two events, the other only one. The MIT version, which the author judged the most correct, confirms S to S really has two cases: a local read hit, and a BusRd from another cache for a block this cache also shares. The note also carries an unsure rule: on BusRdX or a flush, a line in M, E or S must quickly be marked invalid. The longest paragraph is about precision: M and E are always exact, S may be stale. If one cache invalidates an S line, another may in fact be the sole owner, yet it will not promote to E, because caches do not broadcast invalidations and nobody keeps a count of copies. Write paths: writing an S line first invalidates the other sharers (the note says "local to E, others to I") then writes, ending in M; writing an I line first re-reads through the cache controller, landing in E or S, then writes, ending in M. Hence a read-modify-write needs two bus requests unless the line is already in E.二つの出典から貼られた三枚の状態図が、著者の最も鋭い問いを生んだ。ある図では S→S の自己ループに二つのイベントがあり、別の図では一つしかない。最も正しいと判断した MIT 版は、S→S に確かに二つの場合があることを裏付ける。ローカル読み取りのヒットと、このキャッシュも共有するブロックへの他キャッシュからの BusRd である。確信のない規則も残る。BusRdX か flush を聞いたら、M、E、S のラインは速やかに無効にする。最も長い段落は正確さについてで、M と E は常に正確、S は古くなり得る。あるキャッシュが S のラインを無効化すると、別のキャッシュが実際には独占しているかもしれないが、E には昇格しない。キャッシュは無効化を放送せず、誰もコピーの数を数えていないからだ。書き込み経路は、S のラインならまず他の共有者を無効化し(ノートでは「ローカルを E に、他を I に」)、書いて M になる。I のラインならまずキャッシュコントローラ経由で再読み込みして E か S になり、書いて M になる。だから read-modify-write は既に E でない限り二回のバス要求が要る。

兩個短尾巴:一張 MSI 圖顯示沒有 E 的三狀態前身,這正是 E 被發明的原因,否則對私有行的首次寫入仍要一次匯流排交易;以及一篇從硬體觀點談記憶體屏障的中文部落格連結,把 MESI 與 store buffer、invalidate queue 連在一起:核心會緩衝儲存、延後已回應的作廢,所以光靠協定得不到循序一致性,屏障就是用來恢復它。參考 Wikipedia 的 MESI 條目。Two short tails: an MSI diagram showing the three-state ancestor without E, which is why E was invented, since otherwise every first write to a private line still costs a bus transaction; and a link to a Chinese-language blog post on memory barriers from the hardware side, tying MESI to the store buffer and invalidate queue: a core buffers stores and defers acknowledged invalidations, so the protocol alone does not give sequential consistency, and barriers restore it. See the Wikipedia MESI article.二つの短い末尾。E のない三状態の祖先を示す MSI の図、これこそ E が考案された理由で、さもなければ私有ラインへの最初の書き込みでもバストランザクションが要る。そしてハードウェア側からメモリバリアを論じた中国語ブログへのリンクで、MESI をストアバッファと無効化キューに結びつける。コアはストアをバッファし応答済みの無効化を先送りするので、プロトコルだけでは逐次一貫性は得られず、バリアがそれを回復する。参考は Wikipedia の MESI の項目。

要點:M 與 E 精確,S 只是共享的下界。寫 S 或 I 的行要先花一次匯流排請求,所以 read-modify-write 是兩次請求,除非已在 E;MESI 本身不排序儲存,那是屏障的工作。Takeaway: M and E are exact, S is only a lower bound on sharing. A write to an S or I line costs a bus request first, so read-modify-write is two requests unless the line is already E; and MESI by itself does not order stores, that is the job of barriers.要点:M と E は正確で、S は共有の下限にすぎない。S や I のラインへの書き込みはまずバス要求を一回要するので、read-modify-write は既に E でない限り二回の要求になる。MESI 自体はストアを順序付けず、それはバリアの仕事である。

DMA 與快取一致性DMA and cache coherenceDMA とキャッシュ一貫性

來源筆記:Source notes: 出典ノート:dma cache coherence.md

DMA 筆記摘要一篇中文文章,記錄三種做法。最簡單的是把 DMA 緩衝區設為不可快取:最容易做對但代價最大。第二種維持可快取、用軟體維護一致性,規則依方向而定:DMA 從裝置讀進記憶體時,啟動前先作廢涵蓋緩衝區的快取行,之後就不會有過時的行命中;DMA 從記憶體送到裝置時,傳輸前先 clean 這些行(作者旁註「flush??」),也就是把髒資料寫回,裝置才不會讀到舊位元組。傳輸期間 CPU 都不能碰緩衝區:前者會把 DMA 前的內容重新填進快取,後者對 write-back 快取的寫入永遠到不了裝置。這正是 Linux 以 dma_map_single() 實作串流式 DMA 映射的方法(見核心的 DMA API 文件)。The DMA note summarises a Chinese article and records three approaches. The simplest is to make the DMA buffer non-cacheable: easiest to get right, most expensive. The second keeps the buffer cacheable and maintains coherence in software, with a rule per direction: when DMA reads from the device into memory, invalidate the cache lines covering the buffer before starting, so no stale line can hit afterwards; when DMA sends memory to the device, clean the lines before the transfer (the author wrote "flush??" beside it), that is, write back dirty data, so the device does not read old bytes. The CPU must not touch the buffer while the transfer is in flight: in the first case it would re-populate the cache with pre-DMA contents, in the second a write into a write-back cache would never reach the device. This is exactly how Linux implements streaming DMA mappings with dma_map_single() (see the kernel's DMA API documentation).DMA のノートは中国語記事を要約し、三つの方法を記録する。最も単純なのは DMA バッファをキャッシュ不可にすることで、最も間違えにくいが最もコストが高い。二つ目はキャッシュ可能のままソフトウェアで一貫性を維持するもので、規則は方向ごとに決まる。DMA がデバイスからメモリへ読むときは、開始前にバッファを覆うキャッシュラインを無効化し、後で古いラインがヒットしないようにする。DMA がメモリをデバイスへ送るときは、転送前にラインを clean する(著者は横に「flush??」と書いた)、つまりダーティなデータを書き戻し、デバイスが古いバイトを読まないようにする。転送中に CPU がバッファに触れてはならない。前者では DMA 前の内容がキャッシュに再び入り、後者では write-back キャッシュへの書き込みがデバイスに届かない。これがまさに Linux が dma_map_single() でストリーミング DMA マッピングを実装する方法である(カーネルの DMA API ドキュメントを参照)。

第三點是對齊要求,用作者加了眉批的實例說明。兩個毫不相關的全域變數緊鄰放置:The third point is the alignment requirement, illustrated by a worked example the author annotated. Two unrelated globals sit side by side:三つ目は整列の要件で、著者が書き込みを加えた具体例で説明されている。無関係な二つのグローバル変数が隣り合っている。

int temp = 5;
char buffer[64] = { 0 };

在 64 位元組快取行下,temp 與 buffer 的前段共用一條行,buffer 橫跨兩條行。出錯流程:作廢兩條行、啟動 DMA 讀入 buffer,傳到 buffer[3] 時某程式把 temp 改成 6。寫入發生在快取裡,該行變髒,同時裝著 temp 和 buffer 在 DMA 之前的零。傳到 buffer[50] 時另一程式把髒行踢出,寫回把 temp 連同過時的 buffer 位元組寫進記憶體,把 DMA 已送達 buffer[3] 到 buffer[49] 的資料覆寫成傳輸前的值。作者眉批問對 temp 的寫入是否就是設定 dirty 位元的原因,答案是肯定的。結論:DMA 緩衝區的起始位址與大小都必須對齊快取行,才不會與其他資料共用一條行。With 64-byte lines, temp and the first part of buffer share one line and buffer spans two. The failing sequence: invalidate both lines, start a DMA read into buffer, and when the transfer has reached buffer[3] some program writes temp = 6. The write lands in the cache, the line is now dirty and holds temp together with the pre-DMA zeros of buffer. When the transfer has reached buffer[50], another program evicts the dirty line, and the write-back puts temp into memory along with the stale buffer bytes, overwriting what DMA had already delivered to buffer[3] through buffer[49] with the values from before the transfer. The author's margin note asks whether the write to temp is what sets the dirty bit; it is. Conclusion: a DMA buffer must be cache-line aligned in both start address and size, so it never shares a line with anything else.64 バイトのラインでは、temp と buffer の前半は一つのラインを共有し、buffer は二つにまたがる。問題の手順は、両ラインを無効化し、buffer への DMA 読み込みを開始し、転送が buffer[3] に達したところで、あるプログラムが temp = 6 と書く。書き込みはキャッシュ内に落ち、ラインはダーティになって temp と DMA 前の buffer のゼロを一緒に保持する。転送が buffer[50] に達したとき、別のプログラムがそのダーティラインを追い出し、書き戻しが temp を古い buffer のバイトもろともメモリに書き、DMA が既に buffer[3] から buffer[49] に届けていたデータを転送前の値で上書きする。著者の欄外の書き込みは temp への書き込みがダーティビットを立てる原因かと問うており、そのとおりである。結論は、DMA バッファは開始アドレスも大きさもキャッシュラインに整列し、他のデータとラインを共有しないこと。

管線與計算機結構課程筆記Pipelining and the architecture course notesパイプラインと計算機アーキテクチャ講義ノート

來源筆記:Source notes: 出典ノート:pipeline.md, 計算機結構筆記.md

管線筆記幾乎全是圖片:第一張是經典的五級資料路徑;第二張由作者加註,顯示載入指令在執行階段算出位址,再到記憶體讀出該位址的值,於寫回階段放進暫存器。唯一的文字是華盛頓大學 CSE410 管線講義的公開連結:cse410-10-pipelining-a.pdf。The pipeline note is almost entirely pictures: the first the classic five-stage datapath; the second, captioned by the author, a load whose address is computed in the execute stage, after which memory is read at that address and the value placed in a register at write-back. The only text is the public link to the University of Washington CSE410 lecture on pipelining: cse410-10-pipelining-a.pdf.パイプラインのノートはほぼ図だけである。一枚目は古典的な五段のデータパス、二枚目は著者が注を付けたもので、ロード命令が実行段でアドレスを計算し、そのアドレスのメモリを読み、ライトバック段で値をレジスタに入れる。唯一の文章はワシントン大学 CSE410 のパイプライン講義への公開リンクである:cse410-10-pipelining-a.pdf。

「計算機結構筆記」是成大計算機結構課程的上課隨手清單,最上面是評分方式「quiz (20)、homework」。依授課者提出的順序:The 計算機結構筆記 file is a lecture scratch list from the NCKU computer-architecture course, with the grading line "quiz (20), homework" at the top. In the order the lecturer raised them:「計算機結構筆記」は成功大学の計算機アーキテクチャ講義で取った走り書きのリストで、先頭に評価方法「quiz (20)、homework」がある。講師が挙げた順に:

  • 為安全性客製化的 CPU、由專用小型 MCU 處理指紋的「security enclave」、沒有答案的「micro operation?」。Custom CPUs built for security, a "security enclave" for fingerprints handled by a dedicated small MCU, an unanswered "micro operation?".セキュリティのためのカスタム CPU、専用の小さな MCU で指紋を扱う「security enclave」、答えのない「micro operation?」。
  • 領域專用架構(DSA)以 TPU 與 GPU 為例、VLIW、用於回音消除的 DSP、「架構的第二個黃金年代?」、異質架構與互連、要查的「cs161??」。Domain-specific architectures (DSA) with the TPU and GPU as examples, VLIW, DSPs for echo cancellation, "a second golden age of architecture?", heterogeneous architectures and their interconnect, "cs161??" to look up.ドメイン特化アーキテクチャ(DSA)の例としての TPU と GPU、VLIW、エコーキャンセル用の DSP、「アーキテクチャの第二の黄金期か」、異種アーキテクチャとその相互接続、調べるべき「cs161??」。
  • 平行度、效能量測與改善;ARM NEON;指令延遲與排程;資料危障;取樣與量化的插話(取樣頻率為訊號最高頻率的兩倍);二的補數的符號擴展。Parallelism, performance measurement and improvement; ARM NEON; instruction latency and scheduling; data hazards; an aside on sampling and quantisation (sampling rate twice the highest signal frequency); sign extension in two's complement.並列度、性能の測定と改善。ARM NEON、命令レイテンシとスケジューリング、データハザード、サンプリングと量子化の余談(サンプリング周波数は信号の最高周波数の二倍)、二の補数の符号拡張。

浮點數區塊最密集。溢位與下溢是「太大與太小」。作者想知道 quiet NaN 與 signaling NaN 的差別,並正確猜測後者是為了發起例外。非正規數和它們填補的「gaps」得到三個問號。bfloat16 記為為 TPU 而做的格式,與四倍、八倍、半精度並列。還列了二進位浮點轉十進位、SSE 雙精度、精密度與準確度的區別(後者和捨入有關)。授課者說捨入模式「必考」,小考會考浮點數與整數轉換。sse2neon 是在 ARM 上跑 SSE intrinsics 的方法;Kahan 加總在「accuracy vs bandwidth」底下;MIPS 為單、雙精度須有兩套指令集。兩個警告原樣記下:int 轉 float 再轉回 int 不一定相等,很危險;gcc fast-math「會毀掉一些數學運算」。參考:IEEE 754、Kahan 加總、bfloat16、sse2neon。記憶體管理區塊記錄 best-fit(慢)、first-fit、next-fit,Intel 起始位址寫作 0800000 hex,低位址保留給中斷向量表,以及一句 RISC-V RV32。The floating-point block is the densest. Overflow and underflow are "too large and too small". The author wanted the difference between a quiet NaN and a signalling NaN and guessed, correctly, that the latter exists to raise an exception. Denormals and the "gaps" they fill got three question marks. bfloat16 is noted as the format made for the TPU, beside quad, octuple and half precision. Also listed: binary float to decimal conversion, SSE double precision, and precision versus accuracy (the latter tied to rounding). The lecturer said rounding modes "will be on the quiz", as will float-to-int conversion. sse2neon is the way to run SSE intrinsics on ARM; Kahan summation sits under "accuracy vs bandwidth"; MIPS needs two instruction sets for single and double. Two warnings are recorded verbatim: int to float and back does not necessarily give the same int, which is dangerous; and gcc fast-math "will destroy some mathematical operations". References: IEEE 754, Kahan summation, bfloat16, sse2neon. The memory-management block records best-fit (slow), first-fit and next-fit, the Intel start address written as 0800000 hex, low addresses reserved for the interrupt vector table, and a lone RISC-V RV32.浮動小数点のブロックが最も密度が高い。オーバーフローとアンダーフローは「大きすぎると小さすぎる」。著者は quiet NaN と signaling NaN の違いを知りたがり、後者は例外を発生させるためにあると正しく推測した。非正規化数とそれが埋める「gaps」には疑問符が三つ。bfloat16 は TPU のために作られた形式として、四倍、八倍、半精度と並ぶ。二進浮動小数点から十進への変換、SSE の倍精度、精度と正確さの区別(後者は丸めに関係)も列挙。講師は丸めモードは「必ず出る」、浮動小数点と整数の変換も出ると言った。sse2neon は ARM で SSE intrinsics を動かす方法、Kahan の加算は「accuracy vs bandwidth」の下、MIPS は単精度と倍精度に二組の命令セットが要る。二つの警告がそのまま記録されている。int を float にして戻しても同じ int に戻るとは限らず危険であること、gcc の fast-math は「いくつかの数学演算を壊す」こと。参考:IEEE 754、Kahan 加算、bfloat16、sse2neon。メモリ管理のブロックには best-fit(遅い)、first-fit、next-fit、Intel の開始アドレス 0800000 hex、割り込みベクタテーブルのために予約された低アドレス、そして RISC-V RV32 の一言が記録されている。

並行與同步Concurrency and synchronisation並行処理と同期

來源筆記:Source notes: 出典ノート:concurrency and parallism_ 並行和多執行緒程式設計 (上).md, 同步.md, rcu related;lock free.md

並行筆記是並行與多執行緒程式設計課程上半部的一頁上課單句。號誌先出現、互斥鎖後出現;互斥鎖需要硬體的原子機制,號誌建立在計數器上。超純量是廣度,管線是深度。超執行緒是硬體層級,OS 看不見,只以為多了幾個核心,實際上 ALU 等硬體共用。per-CPU 資料只允許某一個核心存取。沒有 OS 也有可再入性問題,因為中斷服務常式隨時會打斷主程式。The concurrency note is a page of one-liners from the first half of a course on concurrent and multithreaded programming. Semaphores came first and mutexes later; a mutex needs an atomic mechanism from the hardware, a semaphore is built on a counter. Superscalar is width, pipelining is depth. Hyper-threading is hardware-level and invisible to the OS, which merely believes it has a few more cores while the ALUs and other units are shared. Per-CPU data may be touched by one core only. Reentrancy problems exist even without an OS, because interrupt service routines can interrupt the main code at any point.並行処理のノートは、並行・マルチスレッドプログラミング講義の前半で取った一行メモの一ページである。セマフォが先、ミューテックスが後で、ミューテックスはハードウェアのアトミック機構を要し、セマフォはカウンタの上に作られる。スーパースカラは幅、パイプラインは深さ。ハイパースレッディングはハードウェア階層で OS には見えず、OS はコアが数個増えたと思うだけで、実際には ALU などは共有される。per-CPU データは一つのコアだけがアクセスできる。OS がなくても再入可能性の問題はあり、割り込みサービスルーチンがいつでもメインコードを中断するからだ。

「同步」筆記記錄 POSIX 號誌的建構函式:The 同步 note records the POSIX semaphore constructor:「同步」のノートは POSIX セマフォのコンストラクタを記録している。

int sem_init(sem_t *sem, int pshared, unsigned int value);

pshared 設定型別:0 代表同一程序內多執行緒的同步;大於 0 表示可共享、用於多個相關程序之間,這要求 sem 本身位於共享記憶體。作者接著問初始值為 0 的號誌目的是什麼,找到一則 Stack Overflow 討論但不太看得懂,便自己推理:在上面 wait 的執行緒要等別人 post 才能動,所以是確保執行順序,是訊號而非鎖。這個推理是對的。「rcu related;lock free」筆記是連結清單,只有一句內容,即讀寫鎖的規則:讀者與讀者不互斥,但讀者與寫者互斥、寫者與寫者也互斥。連結指向 Wikipedia 的 RCU 條目與公開的 sysprog 課程筆記 Linux RCU、並行中的原子操作。那句規則正是 RCU 的動機:讀者遠多於寫者時連讀者端的鎖都太貴,RCU 讓讀者不加鎖,由寫者發布新副本並在釋放舊副本前等待寬限期。pshared sets the type: 0 means the semaphore synchronises threads of one process; greater than 0 means it can be shared between related processes, which requires sem itself to live in shared memory. The author then asked what a semaphore initialised to 0 is for, found a Stack Overflow thread he did not quite follow, and reasoned it out: a thread that waits on it cannot proceed until someone posts, so it enforces ordering, a signal rather than a lock. That reasoning is right. The rcu related; lock free note is a link list with one sentence of content, the reader-writer lock rule: readers do not exclude readers, but readers exclude writers and writers exclude writers. The links point to the Wikipedia RCU article and the public sysprog course notes on Linux RCU and atomics in concurrency. That rule is the motivation for RCU: when readers vastly outnumber writers even the reader-side lock is too expensive, so RCU lets readers run without a lock while writers publish a new copy and wait a grace period before freeing the old one.pshared が型を決める。0 なら同一プロセス内のスレッド間の同期、0 より大きければ関連する複数プロセス間で共有でき、その場合 sem 自体が共有メモリに置かれる必要がある。著者は次に初期値 0 のセマフォは何のためかと問い、Stack Overflow のスレッドを見つけたがよく分からず、自分で推論した。それを wait するスレッドは誰かが post するまで進めないので、実行順序の保証であり、ロックではなく信号である。この推論は正しい。「rcu related;lock free」のノートはリンク集で、内容の文は一つ、リーダ・ライタロックの規則である。読者と読者は排他しないが、読者と書き手は排他し、書き手同士も排他する。リンクは Wikipedia の RCU の項目と公開の sysprog 講義ノート Linux RCU、並行処理におけるアトミック操作を指す。その規則こそ RCU の動機で、読者が書き手よりはるかに多いとき読者側のロックでさえ高くつき、RCU は書き手が新しいコピーを公開して古いコピーの解放前に猶予期間を待つことで、読者をロックなしで走らせる。

要點:初始值為 0 的號誌是訊號而非鎖;互斥鎖是需要原子硬體的號誌;rwlock 的「讀者與寫者互斥」正是 RCU 去掉的代價。Takeaway: a semaphore initialised to 0 is a signal, not a lock; a mutex is a semaphore that needs atomic hardware; and rwlock's "readers exclude writers" is the cost RCU removes.要点:初期値 0 のセマフォはロックではなく信号。ミューテックスはアトミックなハードウェアを要するセマフォ。rwlock の「読者と書き手の排他」こそ RCU が取り除くコストである。

Continuous Runahead 論文The Continuous Runahead paperContinuous Runahead 論文

來源筆記:Source notes: 出典ノート:continous runahead_ transparent hardware acceleration for memory intensive workloads.md

這組裡唯一標了「paper」的筆記,把 Continuous Runahead: Transparent Hardware Acceleration for Memory Intensive Workloads(MICRO 2016)濃縮成關鍵字。runahead 執行是基本概念:核心在長延遲快取失誤上停滯時,繼續推測性地執行失誤之後的指令,不為提交結果,而為發現更多失誤並提早取回。筆記列出對照的兩種傳統預取器,全域歷史緩衝區(GHB)與串流預取器,以及推動論文的指標「runahead 可達的快取失誤」。貢獻是 Continuous Runahead Engine(CRE):位於記憶體控制器的多核心共享加速器,把產生失誤的相依鏈送過去持續執行,而不只在停滯期間 runahead。作者記下它把預取覆蓋率提高到 70%,旁註「原來是多少?」;最後記下 CRE 與 GHB 預取結合最好,因為兩者找到的是不同的失誤。The only note in the group tagged "paper" reduces Continuous Runahead: Transparent Hardware Acceleration for Memory Intensive Workloads (MICRO 2016) to keywords. Runahead execution is the base idea: when the core stalls on a long-latency cache miss, it keeps executing speculatively past the miss, not to commit results but to discover further misses and fetch them early. The note lists the two conventional prefetchers compared against, a global history buffer (GHB) and a stream prefetcher, and the motivating metric, "runahead-reachable cache misses". The contribution is the Continuous Runahead Engine (CRE), a shared multi-core accelerator at the memory controller to which the miss-generating dependence chains are shipped and run continuously, instead of only during a stall. The author recorded that it raises prefetch coverage to 70 percent, asked in the margin "what was it before?", and noted last that CRE combined with GHB prefetching is best, since the two find different misses.このグループで唯一「paper」タグの付いたノートで、Continuous Runahead: Transparent Hardware Acceleration for Memory Intensive Workloads(MICRO 2016)をキーワードに還元している。runahead 実行が基本の考えで、コアが長レイテンシのキャッシュミスで停止したとき、ミスの先を投機的に実行し続ける。結果をコミットするためではなく、さらなるミスを見つけて早めに取りに行くためである。ノートは比較対象の二つの従来型プリフェッチャ、グローバル履歴バッファ(GHB)とストリームプリフェッチャ、そして動機となる指標「runahead で到達可能なキャッシュミス」を挙げる。貢献は Continuous Runahead Engine(CRE)で、メモリコントローラに置かれたマルチコア共有アクセラレータに、ミスを生む依存連鎖を送って連続的に実行させ、停止中だけ先走るのではない。著者はプリフェッチのカバレッジを 70% に高めると記録し、欄外で「元はいくつだったのか」と問い、最後に CRE と GHB プリフェッチの組み合わせが最良だと記した。両者は異なるミスを見つけるからである。

資料結構:紅黑樹與基數樹Data structures: red-black tree and radix treeデータ構造:赤黒木と基数木

來源筆記:Source notes: 出典ノート:資料結構與演算法.md

資料結構筆記是純粹的連結隨手記。紅黑樹底下有一篇中文解說;基數樹底下有中文維基百科條目、兩篇中文部落格,以及一篇談 Linux page cache 中基數樹的文章,核心就是在那裡以頁偏移索引每個檔案的快取頁。作者需要它們的原因可從匯出檔的其他部分看出:他研究的 NOVA 檔案系統把每個 inode 日誌項目的 DRAM 索引放在基數樹裡,並用紅黑樹管理空閒清單。一般理論可看英文維基百科的紅黑樹與基數樹。The data-structures note is a pure link scratchpad. Under red-black tree there is one Chinese explainer; under radix tree the Chinese Wikipedia article, two Chinese blogs, and a post on the radix tree in the Linux page cache, where the kernel indexes each file's cached pages by page offset. Why the author needed them is visible elsewhere in the export: the NOVA file system he was studying keeps its DRAM index of each inode's log entries in a radix tree and manages its free lists with red-black trees. For the general theory see the English Wikipedia pages on the red-black tree and the radix tree.データ構造のノートは純粋なリンクの走り書きである。赤黒木の下には中国語の解説が一つ。基数木の下には中国語版 Wikipedia の項目、中国語のブログが二つ、そして Linux のページキャッシュにおける基数木についての記事があり、カーネルはそこで各ファイルのキャッシュ済みページをページオフセットで索引付けする。著者がこれらを必要とした理由はエクスポートの他の部分から見て取れる。研究していた NOVA ファイルシステムは各 inode のログエントリの DRAM 索引を基数木に置き、空きリストを赤黒木で管理する。一般理論は英語版 Wikipedia の赤黒木と基数木を参照。

未解問題Open questions未解決の問い

來源筆記:Source notes: 出典ノート:mesi protocol(也稱為伊利諾斯協議,是因為該協議由伊利諾斯州立大學提出).md, dma cache coherence.md, 計算機結構筆記.md, 同步.md, continous runahead_ transparent hardware acceleration for memory intensive workloads.md

  • MESI:BusRdX 時寫入者從哪裡取得正確資料,記憶體還是持有者的快取?「聽到 BusRdX 或 flush 就把 M/E/S 標為無效」是對的規則嗎?從 M 做 flush 應該是提供資料而不只是丟棄。MESI: where does the writer fetch the correct data on a BusRdX, memory or the owning cache? Is "mark M/E/S invalid on BusRdX or flush" the right rule, given that a flush from M should supply the data, not just drop it?MESI:BusRdX のとき書き手はどこから正しいデータを得るのか、メモリか所有者のキャッシュか。「BusRdX か flush を聞いたら M/E/S を無効にする」は正しい規則か。M からの flush はデータを供給するもので、単に捨てるものではないはずだ。
  • MESI:為什麼一張圖把 S→S 畫成一個事件、另一張畫成兩個?行在 E 時 read-modify-write 真的只需一次請求?(兩者的答案見上文。)MESI: why does one diagram draw S to S with one event and another with two? Does read-modify-write really need only one request when the line is in E? (Both answered above.)MESI:なぜある図は S→S を一つのイベントで描き、別の図は二つで描くのか。ラインが E のとき read-modify-write は本当に要求一回で済むのか。(どちらも上で答えた。)
  • DMA:「clean」和「flush」是同一件事嗎?(clean 是寫回不作廢;flush 通常指 clean 加作廢。)DMA: is "clean" the same as "flush"? (Clean writes back without invalidating; flush usually means clean plus invalidate.)DMA:「clean」と「flush」は同じか。(clean は無効化せずに書き戻す。flush は通常 clean と無効化の両方。)
  • 計算機結構課:什麼是微運算、quiet NaN 與 signaling NaN 究竟差在哪裡、什麼是非正規數和它們填補的 gaps、「fp fallacy」是什麼、cs161 是哪一門課。Architecture course: what is a micro-operation, what exactly separates quiet and signalling NaNs, what are denormals and the gaps they fill, what is "fp fallacy", and which course is cs161.アーキテクチャ講義:マイクロオペレーションとは何か、quiet NaN と signaling NaN は正確には何が違うのか、非正規化数とそれが埋める gaps とは何か、「fp fallacy」とは何か、cs161 はどの講義か。
  • 同步:初始值為 0 的號誌目的是什麼?(確保順序:等待者阻塞到有人 post。)Synchronisation: what is a semaphore initialised to 0 for? (Ordering: the waiter blocks until someone posts.)同期:初期値 0 のセマフォは何のためか。(順序付け。待つ側は誰かが post するまでブロックされる。)
  • Continuous Runahead:CRE 把預取覆蓋率提高到 70% 之前,原本是多少?Continuous Runahead: what was prefetch coverage before the CRE raised it to 70 percent?Continuous Runahead:CRE がプリフェッチのカバレッジを 70% に高める前は、いくつだったのか。
回到頂端 ↑Back to top ↑ページ上部へ ↑

記憶體內運算與非揮發記憶體檔案系統:論文閱讀筆記Processing-in-memory and NVM file systems: paper-reading notesPIM と不揮発メモリファイルシステム:論文読解ノート

四篇掛著 paper 與 pim 標籤的筆記,反映實驗室的研究主軸是記憶體內運算(PIM):一篇 PIM 程式設計範式論文的精讀、NOVA 非揮發主記憶體檔案系統論文的精讀、兩位同學報告論文的速記,以及一則 Linux 檔案時間戳記的小實驗。內容多為逐段中文摘譯,讀不通處標「??」;疑問集中在本節末尾。Four notes tagged paper and pim, from a lab whose research line is processing-in-memory (PIM): a close reading of one PIM programming-paradigm paper, a close reading of the NOVA file system paper for non-volatile main memory, rapid notes from two labmates' paper reports, and a small experiment on Linux file timestamps. Most of the text is paragraph-by-paragraph Chinese paraphrase marked "??" wherever the author lost the thread; those doubts are gathered at the end of this section.paper と pim のタグを持つ四つのノートで、研究室の研究主軸が processing-in-memory(PIM)であることを映す。PIM プログラミングパラダイム論文の精読、不揮発主記憶向けファイルシステム NOVA の論文の精読、同級生二人の論文発表の速記、Linux ファイルタイムスタンプの小実験からなる。本文の大半は段落ごとの中国語抄訳で、理解できなかった箇所に「??」が付く。疑問は本節末尾にまとめた。

PIM 程式設計範式論文:無線 IoT 應用的 PIM 架構The PIM programming-paradigm paper for wireless IoT無線 IoT 向け PIM アーキテクチャのプログラミングパラダイム論文

來源筆記:Source notes: 出典ノート:a processing-in-memory architecture programming paradigm for wireless IOT applications.md

摘要的四個主張:IoT 能耗很重要;以 multimedia 與 MapReduce 工作負載測試;以 gem5 與 FPGA 實作;大幅降低 cache 與匯流排功耗。引言以 near-data computing 為框架,資料可在 cache 或 SSD 等永久儲存內運算;作者記下的關鍵數字是 Intel Xeon 存取記憶體的能耗為存取 cache 的 19.5 倍。能耗模型用 McPAT。五項貢獻:驅動程式與 API、以系統呼叫實現範式、在 FPGA 上跑範例、與傳統架構比較、展示應用前景。The abstract claims four things: energy matters for IoT; the evaluation uses multimedia and MapReduce workloads; the design is implemented in gem5 and on an FPGA; cache and bus power drop substantially. The introduction frames the work as near-data computing, where data is processed inside caches or persistent storage such as an SSD; the figure the author kept is that an Intel Xeon spends 19.5 times more energy reaching memory than reaching cache. McPAT is the energy model. Five contributions: drivers and an API, the paradigm realised with system calls, example programs on the FPGA, a comparison with a conventional architecture, and an outlook.アブストラクトの主張は四つ。IoT では消費エネルギーが重要、評価は multimedia と MapReduce のワークロード、gem5 と FPGA で実装、キャッシュとバスの消費電力を大幅削減。序論は near-data computing の枠組みで、データをキャッシュ内や SSD などの永続ストレージ内で処理する。著者が書き留めた数字は、Intel Xeon がメモリへ到達するエネルギーがキャッシュへの 19.5 倍というものだ。エネルギーモデルは McPAT。貢献は五つ、ドライバと API、システムコールによるパラダイムの実現、FPGA 上のサンプル実行、従来アーキテクチャとの比較、応用展望である。

目標架構:主處理器是無亂序執行的 ARM;PIM 核心可為 SIMD 機器、類 GPU 多執行緒機器、可重組陣列或多核心。CPU 能存取全部記憶體,但把一段設為不可快取給 PIM 使用;被快取的記憶體對 PIM 唯讀。實作的 PIM 核心是不跑作業系統的簡單 ARM,最多兩顆以縮短模擬時間;雙方各自宣告 buffer,PIM 內建的 DMA 負責搬運。分工:控制密集的工作給 CPU,大規模資料處理給 PIM,分工不當會造成多餘的溝通。傳送:DMA 不走一致性協定,CPU 送資料前先把 cache 寫回記憶體,接收時先使對應 cache line 失效再直接讀記憶體。Target architecture: the host is an in-order ARM; the PIM core may be a SIMD machine, a GPU-like multithreaded machine, a reconfigurable array or a multicore. The CPU addresses all memory but marks one region uncacheable for the PIM; cached memory is read-only to the PIM. The PIM core actually built is a simple ARM with no OS, at most two to keep simulation short; each side declares its own buffers and a DMA inside the PIM moves data between them. Partitioning: control-intensive work goes to the CPU, large-scale data processing to the PIM, and a poor split causes needless communication. Transfer: the DMA follows no coherence protocol, so the CPU flushes its cache before sending and invalidates the matching lines and reads memory directly when receiving.ターゲットアーキテクチャ:ホストはインオーダーの ARM、PIM コアは SIMD マシン、GPU 的なマルチスレッドマシン、再構成可能アレイ、マルチコアのいずれでもよい。CPU は全メモリをアクセスできるが一部領域をキャッシュ不可にして PIM に使わせ、キャッシュされるメモリは PIM から読み出し専用。実装された PIM コアは OS のない単純な ARM で、シミュレーション短縮のため最大二個。両側が自分のバッファを宣言し、PIM 内蔵の DMA がその間を運ぶ。分割は制御集約的な仕事を CPU に、大規模データ処理を PIM に割り当て、分割が悪いと余計な通信が生じる。転送では DMA が一貫性プロトコルに従わないため、CPU は送信前にキャッシュをフラッシュし、受信時は該当ラインを無効化してメモリを直接読む。

軟體層:PIM 無作業系統,韌體內含應用導向的演算法。韌體流程是啟動、等待資料與演算法設定完成、執行、通知驅動程式、停止。PIM_context 讓 PIM 接收 CPU 傳來的程式與資料,含三個指標:User_func_pointer(使用者函式)、PIM_func_pointer(韌體函式)、Vars_pointer(全域變數)。驅動程式四種功能:韌體下載(放到指定位置後放行)、資料傳輸(存在韌體特定位置,運算完取回指定長度)、演算法設定與執行(演算法可由韌體或使用者提供)、狀態確認。API 分 kernel mode(呼叫驅動程式)與 user mode(再包一層);簽名中的「A」作者猜是位址。以 PIM_func 前綴標示在 PIM 執行的函式,PIM_vars 前綴標示 PIM 用的全域變數。Software: the PIM runs no OS; the firmware holds application-targeted algorithms. Its lifecycle is start, wait until data and algorithm are configured, run, notify the driver, stop. PIM_context lets the PIM receive CPU-transferred programs and data through three pointers: User_func_pointer (user function), PIM_func_pointer (firmware functions), Vars_pointer (global variables). The driver offers four services: firmware download (placed at a specified location, then released), data transfer (stored at a specific firmware location, a specific length read back after computation), algorithm set and run (algorithm from firmware or user), and status check. The API splits into kernel mode, which calls the driver, and user mode, which wraps it; the author guesses "A" in the signatures means an address. The PIM_func prefix marks a function that runs on the PIM, PIM_vars a global variable it uses.ソフトウェア:PIM に OS はなく、ファームウェアがアプリケーション向けアルゴリズムを内蔵する。その動作は起動、データとアルゴリズムの設定完了を待つ、実行、ドライバへ通知、停止。PIM_context は三つのポインタ、User_func_pointer(ユーザ関数)、PIM_func_pointer(ファームウェア関数)、Vars_pointer(グローバル変数)を通じて PIM が CPU からのプログラムとデータを受け取る仕組みである。ドライバの機能は四つ、ファームウェアダウンロード(指定位置に置いて実行許可)、データ転送(ファームウェアの特定位置に格納し計算後に指定長を読み戻す)、アルゴリズム設定と実行(ファームウェア提供でもユーザ提供でもよい)、状態確認。API はドライバを呼ぶ kernel mode とそれを包む user mode に分かれ、シグネチャの「A」は著者の推測ではアドレス。PIM_func 接頭辞は PIM 上で動く関数、PIM_vars は PIM が使うグローバル変数を示す。

API 群組API groupAPI グループ函式Functions関数用途Purpose用途
檔案操作File operationsファイル操作get_file_size(A file), read_file(A buffer, A file)取得檔案大小、讀檔進 bufferGet a file size, read a file into a bufferファイルサイズ取得、バッファへ読み込み
函式傳送Function transfer関数転送build_buf(A Obuf, A entry, A Ibuf, len), free_buf(A buffer)把使用者函式送到 PIM 並管理輸入輸出 buffer;entry 指定主函式Send user functions to the PIM and manage its I/O buffers; entry names the main functionユーザ関数を PIM に送り入出力バッファを管理。entry で主関数を指定
驅動程式互動Driver interactionドライバとの対話find_device(A PIM_device), update_firmware(PIM_device, A buffer, len)取得裝置資訊、更新韌體Get device information, update the firmwareデバイス情報取得、ファームウェア更新
運算設定Operational configuration動作設定set_algorithm(PIM_device, alg), get_data(PIM_device, A buffer, len), put_data(PIM_device, A recv_buffer, len), check_status(PIM_device), wait(PIM_device)選演算法、送收資料、查狀態、等待結束Choose the algorithm, send and collect data, query status, wait for completionアルゴリズム選択、データ送受、状態問い合わせ、完了待機

評估平台:gem5 不支援 EPIC 與 VLIW,多核心模擬須共用同一 CPU 模型;PIM 核心用 AtomicSimpleCPU(一指令一週期),主處理器用 O3CPU(五級管線亂序),兩者以系統呼叫溝通。FPGA 平台是兩塊 Xilinx ZC706:主板 Zynq 的 Cortex-A9 當主處理器,從板 FPGA 上自製的 ARM 相容處理器當 PIM 核心,兩板以 FMC 相連;主板透過 chip2chip 以映射位址存取從板的 DDR 與控制暫存器,執行結束時從板送中斷到 AXI 中斷控制器再轉給主處理器。實驗章節只貼了十五張圖,沒有文字。Evaluation platform: gem5 supports neither EPIC nor VLIW and a multicore simulation must share one CPU model; the PIM core uses AtomicSimpleCPU (one instruction per cycle), the host O3CPU (five-stage out-of-order), and they communicate through system calls. The FPGA platform is two Xilinx ZC706 boards: the master's Zynq Cortex-A9 is the host, a self-designed ARM-compatible processor on the slave's FPGA is the PIM core, and the boards connect over FMC; the master reaches the slave's DDR and control registers through chip2chip as mapped address space, and on completion the slave raises an interrupt to the AXI interrupt controller and on to the host. The experiment section is fifteen pasted figures with no text.評価プラットフォーム:gem5 は EPIC も VLIW も非対応で、マルチコアシミュレーションは一種類の CPU モデルを共有する。PIM コアは AtomicSimpleCPU(1 命令 1 サイクル)、ホストは O3CPU(5 段パイプラインのアウトオブオーダー)、両者はシステムコールで通信する。FPGA プラットフォームは Xilinx ZC706 二枚で、マスター側 Zynq の Cortex-A9 がホスト、スレーブ側 FPGA 上の自作 ARM 互換プロセッサが PIM コア、二枚は FMC で接続。マスターは chip2chip 経由でスレーブの DDR と制御レジスタをマップされたアドレスとしてアクセスし、完了時にスレーブが AXI 割り込みコントローラへ割り込みを上げてホストに伝わる。実験章は貼り付けた図 15 枚だけで文章はない。

這篇論文把 PIM 當成沒有作業系統的加速卡:不可快取區段加手動 flush/invalidate 取代 cache coherence,PIM_context 的三個指標傳遞程式與資料,四類驅動功能包成 user mode API。The paper treats the PIM as an accelerator with no OS: an uncacheable region plus manual flush and invalidate replaces cache coherence, the three pointers of PIM_context carry programs and data, and four driver services are wrapped into a user-mode API.この論文は PIM を OS のないアクセラレータとして扱う。キャッシュ不可領域と手動の flush/invalidate でキャッシュ一貫性を代替し、PIM_context の三つのポインタでプログラムとデータを渡し、四つのドライバ機能を user mode API に包む。

NOVA:為非揮發主記憶體設計的日誌結構檔案系統NOVA: a log-structured file system for non-volatile main memoryNOVA:不揮発主記憶向けログ構造ファイルシステム

來源筆記:Source notes: 出典ノート:NOVA file system.md

設計總覽:支援原子更新的 log 在 NVMM 上容易正確實作,隨機存取便宜,多個 log 不影響效能。log 與資料放 NVMM,索引是 DRAM 的 radix tree,葉指向 log entry、entry 指向資料。每個 inode 有自己的 log,跨檔案更新不必同步,且有效 entry 少、掃描快。NOVA 先附加資料再原子性更新 log tail 來 commit,避免 journaling 的重複寫入與 shadow paging 的連鎖更新;跨多個 inode 的操作(如搬移目錄)用只記 log tail 的輕量 journal,而任何 POSIX 操作都不超過四個 inode。Design overview: logs with atomic updates are easy to implement correctly in NVMM, random access is cheap, and many logs cost nothing. Logs and data live in NVMM; indexes are DRAM radix trees whose leaves point to log entries, which point to data. Each inode has its own log, so updates across files need no synchronisation and the few valid entries scan fast. NOVA appends data, then atomically updates the log tail to commit, avoiding the duplicate writes of journaling and the cascading updates of shadow paging; operations spanning several inodes, such as moving a directory, use a lightweight journal that records only log tails, and no POSIX operation touches more than four inodes.設計概要:原子更新を持つログは NVMM 上で正しく実装しやすく、ランダムアクセスは安く、複数ログでも性能に影響しない。ログとデータは NVMM に、索引は DRAM の radix tree に置き、葉がログエントリを、エントリがデータを指す。各 inode は自分のログを持ち、ファイル間の更新に同期は不要で、有効エントリが少なく走査が速い。NOVA はデータを追記してからログ末尾を原子的に更新してコミットし、journaling の二重書き込みと shadow paging の連鎖更新を避ける。ディレクトリ移動など複数 inode にまたがる操作はログ末尾だけを記録する軽量ジャーナルを使い、POSIX 操作で 4 個を超える inode に触れるものはない。

log 是 4 KB NVMM page 的單向鏈結串列,每頁尾端放下一頁指標;三個優點是配置自由、可以 page 為單位清理、回收過時頁只需幾個指標指派。log 不含檔案資料,只附加描述寫入並指向資料 page 的 metadata,檔案資料採 copy-on-write。四個理由:log 短、recovery 快;GC 不必搬出檔案資料;回收與配置只是 DRAM free list 的加入與移除;回收快,重寫入負載下仍維持效能與高 NVMM 利用率。The log is a singly linked list of 4 KB NVMM pages with the next-page pointer at the end of each page; three advantages are free allocation, page-by-page cleaning, and reclaiming a stale page with a few pointer assignments. The log holds no file data: only metadata describing the write and pointing to data pages is appended, and file data is copy-on-write. Four reasons: a shorter log speeds recovery; GC never copies file data out of a log page; reclaiming and allocating pages is just adding to and removing from DRAM free lists; fast reclamation keeps performance and NVMM utilisation high under heavy writes.ログは 4 KB の NVMM ページの単方向連結リストで、各ページ末尾に次ページへのポインタを置く。利点は三つ、割り当てが自由、ページ単位でクリーニングできる、古いページの回収が数個のポインタ代入で済む。ログはファイルデータを含まず、書き込みを記述しデータページを指すメタデータだけを追記し、ファイルデータは copy-on-write。理由は四つ、ログが短く回復が速い、GC でファイルデータをログから移す必要がない、回収と割り当ては DRAM フリーリストの追加と削除だけ、回収が速く重い書き込みでも性能と NVMM 利用率を高く保てる。

媒體上有四個區域:superblock 與 recovery inode、journal、inode table、log/data page;recovery inode 讓乾淨關機後的 remount 加速。每個 CPU 有自己的 inode table、journal 與 free page list 以避免全域鎖。inode table 以 round-robin 分到各核心,每個是 2 MB 陣列、inode 對齊 128 byte,滿了就鏈上一個 2 MB sub-table;一位同學解釋 inode 編號分段,1 到 10 在一個核心、11 到 20 在下一個。每個 inode 前有 valid bit,無效者被新檔案重用;per-CPU 表也讓恢復時能平行掃描。inode 內有指向自己 log head 與 tail 的指標,第一次存取時從頭掃描 log 重建 DRAM 結構。The media has four regions: superblock and recovery inode, journals, inode tables, log and data pages; the recovery inode speeds a remount after a clean shutdown. Each CPU has its own inode table, journal and free-page list to avoid global locking. Inode tables are spread round-robin across cores, each a 2 MB array with inodes aligned to 128 bytes, and a full table chains on another 2 MB sub-table; a labmate explained inode numbers are striped, 1 to 10 on one core and 11 to 20 on the next. A valid bit precedes each inode and an invalid one is reused by a new file; per-CPU tables also allow parallel scanning on recovery. An inode holds head and tail pointers to its log, and on first access NOVA scans the log to rebuild the DRAM structures.媒体上の領域は四つ、superblock と recovery inode、ジャーナル、inode テーブル、ログ/データページ。recovery inode はクリーンシャットダウン後の再マウントを速める。各 CPU は自分の inode テーブル、ジャーナル、フリーページリストを持ちグローバルロックを避ける。inode テーブルはラウンドロビンで各コアに分散され、各 2 MB の配列で inode は 128 バイト整列、満杯になれば 2 MB のサブテーブルを連結する。同級生の説明では inode 番号は区間分けされ、1 から 10 がひとつのコア、11 から 20 が次のコア。各 inode の先頭に valid bit があり、無効なものは新しいファイルに再利用される。CPU ごとのテーブルは回復時の並列走査も可能にする。inode は自分のログの head と tail を指すポインタを持ち、初回アクセス時にログを走査して DRAM 構造を再構築する。

journal 是每 CPU 一個 4 KB 環狀緩衝區,帶 enqueue 與 dequeue 指標對。跨 inode 的更新先附加 log entry,再把每個受影響的 log tail 寫到 enqueue 位置並推進 enqueue,更新完成後把 dequeue 設成等於 enqueue 來 commit;create 的 journal 記錄目錄的 log tail 指標與新 inode 的 valid bit。斷電恢復時回滾 dequeue 與 enqueue 之間的更新。每核心一次只有一筆交易,VFS 鎖住目錄操作牽涉的所有 inode,所以同時的交易不會碰同一個 inode。空間管理:NVMM 切成每 CPU 一個 pool,空閒 page 清單放 DRAM,pool 用盡時從最大的 pool 配置並以 per-pool lock 保護;free list 用紅黑樹依位址排序,便於合併並提供 O(log n) 釋放。allocator 狀態運作期間不存 NVMM,正常關機時寫到 recovery inode 的 log,斷電後掃描全部 inode 的 log 重建。The journal is one 4 KB circular buffer per CPU with an enqueue and dequeue pointer pair. A multi-inode update appends the log entries, writes each affected log tail at enqueue and advances enqueue, then sets dequeue equal to enqueue to commit; for a create the journal holds the directory's log-tail pointer and the new inode's valid bit. Recovery after power failure rolls back anything between dequeue and enqueue. Each core has one transaction at a time, and the VFS locks every inode a directory operation touches, so concurrent transactions never share an inode. Space management: NVMM is split into one pool per CPU with free-page lists in DRAM; a dry pool borrows from the largest pool under per-pool locks; free lists are sorted by address in a red-black tree for efficient merging and O(log n) deallocation. Allocator state is not stored in NVMM during operation, is written to the recovery inode's log on a clean shutdown, and after a power failure is rebuilt by scanning all inode logs.ジャーナルは CPU ごとに一つの 4 KB 環状バッファで、enqueue と dequeue のポインタ対を持つ。複数 inode の更新はログエントリを追記し、影響する各ログ末尾を enqueue 位置に書いて enqueue を進め、dequeue を enqueue と等しくしてコミットする。create ではディレクトリのログ末尾ポインタと新 inode の valid bit を記録する。電源断後の回復では dequeue と enqueue の間の更新をロールバックする。コアごとにトランザクションは一つずつで、VFS がディレクトリ操作の触れる全 inode をロックするので並行トランザクションが同じ inode を共有することはない。領域管理:NVMM は CPU ごとに一つのプールに分割され、空きページリストは DRAM に置く。プールが尽きたら最大のプールからプールごとのロックの下で借りる。フリーリストは赤黒木でアドレス順に保ち、効率的な併合と O(log n) の解放を得る。アロケータの状態は運用中は NVMM に保存せず、クリーンシャットダウン時に recovery inode のログへ書き、電源断の後は全 inode のログを走査して再構築する。

原子性靠三種機制:64 位元原子的 in-place 寫入直接改某些 metadata(如讀取時的 atime)並更新 log tail 指標來 commit;只改單一 inode 的操作(write、msync、chmod)記在該 inode 的 log,各 log 彼此獨立;跨 inode 的目錄操作(create、unlink、rename)用輕量 journal,任何時候不超過 64 byte,最複雜的 rename 牽涉四個 inode,每個 16 byte(8 byte 是 log tail 指標的位址、8 byte 是其值)。寫入順序三條規則:更新 tail 前先 commit 資料與 log entry;傳播更新前先 commit journal;回收舊版前先 commit 新版資料 page。支援 clflushopt、clwb、pcommit 的平台:附加 entry,clwb 寫回受影響的 cache line,sfence 加 pcommit 強迫更新到 NVMM 控制器,再一個 sfence 避免 tail 更新搶先;否則用 movntq 繞過 cache 直寫,搭配 clflush 與 sfence。Atomicity rests on three mechanisms: 64-bit atomic in-place writes modify some metadata directly (such as atime on read) and commit log updates through the log-tail pointer; single-inode operations (write, msync, chmod) go into that inode's log, and logs are independent; multi-inode directory operations (create, unlink, rename) use the lightweight journal, which never exceeds 64 bytes, the most complex rename touching four inodes at 16 bytes each (8 for the address of the log-tail pointer, 8 for its value). Three ordering rules: commit data and log entries before updating the tail; commit journal data before propagating updates; commit new data pages before reclaiming the old version. With clflushopt, clwb and pcommit: append the entry, write back the affected cache lines with clwb, issue sfence and pcommit to force the updates to the NVMM controller, then a second sfence so the tail update cannot run ahead; otherwise movntq bypasses the cache, paired with clflush and sfence.原子性は三つの仕組みに基づく。64 ビット原子の in-place 書き込みが一部のメタデータ(読み出し時の atime など)を直接変更し、ログ末尾ポインタでログへの更新をコミットする。単一 inode の操作(write、msync、chmod)はその inode のログに入り、各ログは独立。inode をまたぐディレクトリ操作(create、unlink、rename)は軽量ジャーナルを使い、常に 64 バイト以下で、最も複雑な rename は 4 個の inode に各 16 バイト(ログ末尾ポインタのアドレスに 8、その値に 8)。順序規則は三つ、末尾更新前にデータとログエントリをコミット、更新伝播前にジャーナルをコミット、旧版回収前に新データページをコミット。clflushopt、clwb、pcommit があれば、エントリを追記し、影響するキャッシュラインを clwb で書き戻し、sfence と pcommit で更新を NVMM コントローラへ強制し、二つ目の sfence で末尾更新の先行を防ぐ。なければ movntq でキャッシュを迂回し、clflush と sfence を組み合わせる。

目錄由目錄 inode 的 log 和 DRAM 的 radix tree 組成。log 有兩種 entry:dentry 含子項名稱、inode 編號與時間戳記(讓 mtime 與 ctime 隨操作原子性更新),inode update entry 記錄目錄 inode 本身的變動(chown、chmod)。建立、刪除或重新命名子項時附加一個 dentry,刪除用的 dentry 把 inode 編號設為 0 以區別於建立。radix tree 以名稱的雜湊值為鍵,葉指向 log 內的 dentry。建立檔案 zoo(目錄已有 bar):選一個未用 inode 初始化,在目錄 log 附加 create dentry,用目前 CPU 的 journal 原子性更新目錄 log tail 並設 valid bit,再加進 radix tree。刪除需減少 link count 並從目錄移除:在目錄 log 附加 delete dentry、在檔案 log 附加 inode update entry、用 journal 原子性更新兩個 inode、再傳播到 radix tree。A directory is its inode's log plus a DRAM radix tree. The log has two entry kinds: a dentry with the child's name, inode number and a timestamp (which updates mtime and ctime atomically with the operation), and an inode update entry for changes to the directory inode itself (chown, chmod). Creating, deleting or renaming a child appends a dentry, and a delete dentry has inode number 0 to distinguish it from a create. The radix tree is keyed by the hash of the name and its leaves point to dentries in the log. Creating file zoo in a directory holding bar: pick and initialise an unused inode, append a create dentry to the directory log, use the current CPU's journal to atomically update the directory's log tail and set the valid bit, then add zoo to the radix tree. Deleting means decrementing the link count and removing the file from its directory: append a delete dentry to the directory log and an inode update entry to the file log, update both inodes atomically through the journal, then propagate to the radix tree.ディレクトリはその inode のログと DRAM の radix tree からなる。ログのエントリは二種、子の名前、inode 番号、タイムスタンプ(mtime と ctime を操作と同時に原子的に更新)を持つ dentry と、ディレクトリ inode 自体の変更(chown、chmod)を記す inode update entry。子の作成、削除、改名で dentry を追記し、削除用 dentry は inode 番号を 0 にして作成と区別する。radix tree の鍵は名前のハッシュ値で、葉はログ内の dentry を指す。bar を含むディレクトリにファイル zoo を作るには、未使用 inode を選んで初期化し、ディレクトリのログに create dentry を追記し、現在の CPU のジャーナルでディレクトリのログ末尾更新と valid bit 設定を原子的に行い、zoo を radix tree に加える。削除はリンク数の減少とディレクトリからの除去を要し、ディレクトリのログに delete dentry、ファイルのログに inode update entry を追記し、ジャーナルで両 inode を原子的に更新し、radix tree に伝播する。

檔案寫入同時用 log 與 copy-on-write:前者以低開銷維持原子性,後者縮小 log 並簡化 GC。檔案 log 的 file write entry 指向寫入修改的資料 page 並帶時間戳記與檔案大小;DRAM 的 radix tree 把檔案 offset 映射到 write entry。找不到夠大的連續 page 時,一次寫入拆成多個 entry,再以單一次 tail 更新 commit。讀取以 64 位元原子寫入更新 atime,用 radix tree 找 page,再從 NVMM 複製到使用者 buffer。實例以 <pgoff, num pages> 表示:log 已有 <0,1> 與 <1,2>(4 KB 與 8 KB),第三個 8 KB 寫入 <2,2> 進行中。NOVA 填好資料 page,附加 <2,2> entry,原子性更新 tail,讓 radix tree 的 offset 2 指向新 entry;page 2 的舊 NVMM page 立刻歸還 free list。期間 per-inode lock 保護 log 與 radix tree,write 返回時所有更新已永久在 NVMM。作者看不懂為何 offset 2 與 3 都指向 <2,2>:<1,2> 涵蓋 page 1 與 2,新寫入覆蓋 page 2 與 3,所以 page 1 仍屬舊 entry,page 2 的映射改指新 entry。GC 只留 fast GC 與 thorough GC 兩個標題和一張圖。File writes use both the log and copy-on-write: the first keeps atomicity cheap, the second shrinks the log and simplifies GC. A file write entry points to the data pages a write modified and carries a timestamp and the file size; a DRAM radix tree maps file offsets to write entries. When enough contiguous pages cannot be found, one write is split into several entries and committed with a single tail update. A read updates atime with a 64-bit atomic write, locates pages through the radix tree, and copies from NVMM to the user buffer. The worked example uses <pgoff, num pages>: the log holds <0,1> and <1,2> (4 KB and 8 KB) and a third 8 KB write <2,2> is in progress. NOVA fills the data pages, appends the <2,2> entry, atomically updates the tail, and points offset 2 in the radix tree at the new entry; the old NVMM page for page 2 returns to the free list at once. A per-inode lock protects the log and tree meanwhile, and when write returns everything is permanent in NVMM. The author could not see why offsets 2 and 3 both point to <2,2>: <1,2> covers pages 1 and 2, the new write overwrites pages 2 and 3, so page 1 stays with the old entry and page 2 moves to the new one. GC is left as two bare headings, fast GC and thorough GC, plus one figure.ファイル書き込みはログと copy-on-write の両方を使い、前者は原子性を安く保ち、後者はログを縮め GC を単純にする。file write entry は書き込みが変更したデータページを指し、タイムスタンプとファイルサイズを伴う。DRAM の radix tree がファイルオフセットを write entry に対応付ける。十分な連続ページがなければ一回の書き込みを複数エントリに分割し、一回の末尾更新でコミットする。読み出しは 64 ビット原子書き込みで atime を更新し、radix tree でページを探し、NVMM からユーザバッファへコピーする。例題は <pgoff, num pages> で表し、ログには <0,1> と <1,2>(4 KB と 8 KB)があり、三番目の 8 KB の書き込み <2,2> が進行中。NOVA はデータページを埋め、<2,2> エントリを追記し、末尾を原子的に更新し、radix tree のオフセット 2 を新エントリに向ける。ページ 2 の旧 NVMM ページは直ちにフリーリストへ戻る。その間 inode ごとのロックがログと木を守り、write が戻る時点で全更新は NVMM に永続化されている。著者はなぜオフセット 2 と 3 の両方が <2,2> を指すのか分からないとしたが、<1,2> はページ 1 と 2 を覆い、新しい書き込みがページ 2 と 3 を上書きするので、ページ 1 は旧エントリのまま、ページ 2 が新エントリへ移るのである。GC は fast GC と thorough GC の見出し二つと図一枚だけ。

筆記最後是編譯步驟:在 apt 來源加入 xenial-security,安裝 linux-headers-4.4.0-130-generic,修改 Makefile 後 make。The note ends with a build recipe: add the xenial-security line to the apt sources, install linux-headers-4.4.0-130-generic, adjust the Makefile, then run make.ノートの最後はビルド手順で、apt ソースに xenial-security の行を追加し、linux-headers-4.4.0-130-generic を入れ、Makefile を修正して make する。

deb http://security.ubuntu.com/ubuntu xenial-security main
# add to the apt source list, then:
apt-get install linux-headers-4.4.0-130-generic
# adjust the Makefile for these headers, then
make

NOVA 的三層原子性:單一 inode 靠「附加 entry、再以 64 位元原子寫入更新 log tail」;跨 inode 的目錄操作靠只記 log tail、不超過 64 byte 的 journal;寫入順序由 clwb → sfence → pcommit → sfence(或 movntq + clflush + sfence)保證。NOVA's three tiers of atomicity: a single inode uses "append the entry, then update the log tail with a 64-bit atomic write"; a directory operation across inodes uses a journal of at most 64 bytes holding only log tails; and write ordering is clwb, then sfence, then pcommit, then sfence (or movntq plus clflush plus sfence).NOVA の三段階の原子性。単一 inode は「エントリを追記し、64 ビット原子書き込みでログ末尾を更新」、inode をまたぐディレクトリ操作はログ末尾だけを持つ 64 バイト以内のジャーナル、書き込み順序は clwb → sfence → pcommit → sfence(または movntq + clflush + sfence)である。

同學的論文報告:近記憶體運算的並行資料結構與 2017 年 PIM 綜述Labmates' paper reports: concurrent data structures for near-memory computing and a 2017 PIM survey同級生の論文発表:近メモリ計算向け並行データ構造と 2017 年の PIM サーベイ

來源筆記:Source notes: 出典ノート:paper report of others.md

9 月 16 日群組會議的速記,幾乎每行都是關鍵字加問號。第一篇談近記憶體運算的並行資料結構,重點是把 PIM 也改成可並行:PIM 之間可以溝通但不能存取彼此的 vault;HMC 1.0 似乎只能 read 與 write;效能模型假設 CPU 到 PIM 與 PIM 到 PIM 的延遲相同(r3 = 1);提到 flat combining、linked list、skip list(有排序,複雜度從 n 降到 log n)與 lock-free FIFO queue;把資料拆到不同 PIM 的 vault 值得注意,隨之而來的是負載平衡問題;pipelining 可以把延遲藏起來。Rapid notes from the group meeting on 16 September, nearly every line a keyword with a question mark. The first paper is about concurrent data structures for near-memory computing, the point being to make the PIM itself concurrent: PIMs can communicate but cannot access each other's vault; HMC 1.0 seems to offer only read and write; the performance model assumes CPU-to-PIM and PIM-to-PIM latency are equal (r3 = 1); the talk covered flat combining, linked lists, skip lists (sorted, complexity from n down to log n) and a lock-free FIFO queue; splitting data across the vaults of different PIMs is worth noting and brings a load-balance problem; pipelining can hide latency.9 月 16 日のグループミーティングの速記で、ほぼ全行がキーワードと疑問符。一本目は近メモリ計算向けの並行データ構造の論文で、要点は PIM 自体を並行化すること。PIM 同士は通信できるが互いの vault にはアクセスできない、HMC 1.0 は read と write しかできないらしい、性能モデルは CPU と PIM 間、PIM と PIM 間のレイテンシを同じと仮定(r3 = 1)、flat combining、連結リスト、skip list(ソート済みで計算量が n から log n へ)、lock-free FIFO queue に言及、データを別々の PIM の vault に分割する点は注目に値し負荷分散問題を伴う、パイプライン化でレイテンシを隠せる。

第二篇是 2017 年的 PIM 綜述,記下的記憶體技術要點:FeRAM 聽說最近有突破;SSD 有寫入放大,erase 一次一大塊而 write 很小塊,所以最好循序寫入,不能 in-place update,實務上寫到新區塊、舊的標為垃圾,常見用 DRAM 做約千分之一容量的 write buffer;PCM 的 reset 需要高溫,有熱干擾與損壞問題,但比很多 NVM 省電;MRAM 可當主記憶體、儲存與晶片內 cache,當主記憶體時可略過命中率太低的 row buffer,放進 L1 效能差異不大卻大量省電;RHCA 與 LHCA 是同層不同材料對不同層不同材料;指導教授補充尺寸越大成本越高,SRAM 越小越快但越貴;還有干擾問題,以及 read and restore:讀取本身可能是破壞性的,讀完要寫回。The second is a 2017 PIM survey; the memory-technology points recorded: FeRAM is said to have had a recent breakthrough; SSDs suffer write amplification because an erase covers a large block while a write is small, so sequential writes are best, they cannot update in place and instead write to a fresh block and mark the old one as garbage, and they commonly carry a DRAM write buffer of about one thousandth of capacity; PCM reset needs high temperature, bringing thermal disturbance and damage problems, though PCM uses less power than many NVMs; MRAM can serve as main memory, storage or on-chip cache, as main memory it can bypass the row buffer whose hit rate is too low, and in L1 it changes performance little but saves much power; RHCA versus LHCA is different materials in one layer versus in different layers; the advisor added that larger size means higher cost and smaller SRAM is faster but dearer; there is a disturbance problem; and "read and restore" means a read may be destructive, so the value must be written back.二本目は 2017 年の PIM サーベイで、記録されたメモリ技術の要点は次のとおり。FeRAM は最近ブレークスルーがあったらしい。SSD は消去が大ブロック単位で書き込みが小さいため書き込み増幅があり、順次書き込みが望ましく、in-place 更新ができず新ブロックに書いて旧ブロックをゴミ扱いにし、容量の千分の一程度の DRAM 製 write buffer がよくある。PCM の reset は高温を要し熱擾乱や損傷の問題があるが、多くの NVM より省電力。MRAM は主記憶、ストレージ、オンチップキャッシュに使え、主記憶ではヒット率が低すぎる row buffer を迂回でき、L1 に入れても性能差は小さいが大幅に省電力。RHCA と LHCA は同一層で異なる材料か異なる層で異なる材料か。指導教員はサイズが大きいほどコストが高く、SRAM は小さいほど速いが高価と補足。擾乱の問題もあり、read and restore とは読み出しが破壊的でありうるため値を書き戻すことを指す。

Linux 檔案的三種時間戳記:atime、ctime、mtimeThe three Linux file timestamps: atime, ctime and mtimeLinux ファイルの三つのタイムスタンプ:atime、ctime、mtime

來源筆記:Source notes: 出典ノート:一些linux file system的屬性.md

讀 NOVA 時的背景補課。UNIX 的三種時間戳記:atime(access time)是上次被讀取的時間;ctime(status change time)是屬性或內容上次被修改的時間;mtime(modified time)是內容上次被修改的時間。筆記用 showTime.sh 以 ls -lc、ls -lu、ls -l 印出三者驗證。Background study done while reading NOVA. UNIX keeps three timestamps: atime (access time) is when the file was last read; ctime (status change time) is when its attributes or contents last changed; mtime (modified time) is when its contents last changed. The note verifies this with showTime.sh, which prints the three using ls -lc, ls -lu and ls -l.NOVA を読む際の背景学習。UNIX のタイムスタンプは三種類、atime(access time)は最後に読まれた時刻、ctime(status change time)は属性または内容が最後に変更された時刻、mtime(modified time)は内容が最後に変更された時刻。ノートは showTime.sh で ls -lc、ls -lu、ls -l を使い三つを表示して検証する。

#!/bin/bash
echo "ctime: $(ls -lc newFile | awk '{print $6, $7, $8}')"
echo "atime: $(ls -lu newFile | awk '{print $6, $7, $8}')"
echo "mtime: $(ls -l newFile | awk '{print $6, $7, $8}')"

exit 0;

實驗四步,每步隔一分鐘:touch newFile 後三者相同(23:14);echo "1st modified" > newFile 後 ctime 與 mtime 變 23:15,atime 不變;cat newFile 後只有 atime 變 23:16;chmod g+wx newFile 後只有 ctime 變 23:17。結論:ls -l 顯示的是 mtime;touch 更新三者;改內容更新 ctime 與 mtime;僅讀取或另存新檔只改 atime;僅改屬性(權限、檔名、擁有者、suid、ACL、chattr)只改 ctime。atime 最常變動,可關閉以增進 I/O,尤其在多人多工、小檔案多與筆電環境:掛載選項加 noatime,或以 chattr +A 固定(chattr 只適用於 ext2/3/4)。Four steps a minute apart: after touch newFile all three agree (23:14); after echo "1st modified" > newFile ctime and mtime move to 23:15 and atime stays; after cat newFile only atime moves to 23:16; after chmod g+wx newFile only ctime moves to 23:17. Conclusions: ls -l shows mtime; touch updates all three; changing content updates ctime and mtime; merely reading or saving-as changes only atime; changing only attributes (permissions, name, owner, suid, ACL, chattr) changes only ctime. atime changes most often and can be switched off to improve I/O, especially on multi-user systems, with many small files, or on laptops: add noatime to the mount options, or freeze it with chattr +A (chattr applies only to ext2/3/4).一分間隔の四段階。touch newFile の後は三つが一致(23:14)、echo "1st modified" > newFile の後は ctime と mtime が 23:15 になり atime はそのまま、cat newFile の後は atime だけ 23:16、chmod g+wx newFile の後は ctime だけ 23:17。結論は、ls -l が示すのは mtime、touch は三つすべてを更新、内容変更は ctime と mtime を更新、読み出しや別名保存だけなら atime のみ、属性(権限、名前、所有者、suid、ACL、chattr)だけの変更は ctime のみ。atime は最も頻繁に変わり、I/O 向上のため無効化できる。特にマルチユーザ環境、小ファイルの多い環境、ノート PC で有効で、マウントオプションに noatime を加えるか chattr +A で固定する(chattr は ext2/3/4 のみ)。

作者留下的疑問Open questions the author left著者が残した疑問

來源筆記:Source notes: 出典ノート:a processing-in-memory architecture programming paradigm for wireless IOT applications.md, NOVA file system.md, paper report of others.md

  • PIM 論文:PIM_context 究竟如何讓 PIM 接收 CPU 傳來的程式?為何 PIM 要呼叫 CPU 程式裡的使用者函式?「選擇韌體中的演算法」怎麼選?CPU 與 PIM 之間的系統呼叫是軟體中斷嗎?從板的中斷是非同步的嗎?PIM paper: how exactly does PIM_context let the PIM receive programs from the CPU? Why would the PIM call user functions that live in the CPU program? How is "choosing the algorithm in the firmware" done? Are the system calls between CPU and PIM software interrupts? Is the slave board's interrupt asynchronous?PIM 論文:PIM_context は具体的にどう CPU からのプログラムを PIM に受け取らせるのか。なぜ PIM が CPU プログラム側のユーザ関数を呼ぶのか。「ファームウェア内のアルゴリズムを選ぶ」とはどう行うのか。CPU と PIM 間のシステムコールはソフトウェア割り込みか。スレーブボードの割り込みは非同期か。
  • NOVA:radix tree 是全 CPU 共用還是每個目錄一棵?inode 為何說「對齊 128 byte」?sub-table 怎麼延伸?「把 dequeue 更新到 enqueue」是什麼意思?16 byte 中的 value 是什麼?為何 read 也要 locate page?「最大的 pool」是剩餘最多的嗎?allocator 的大小為何會變?recovery inode 也有 head 與 tail 嗎?寫入期間為何需要 per-inode lock?NOVA: is the radix tree shared by all CPUs or one per directory? Why "aligned to 128 bytes"? How is a sub-table extended? What does "update dequeue to enqueue" mean? What is the "value" in the 16 bytes? Why does a read need to locate pages? Is "the largest pool" the one with the most free space? Why would the allocator's size change? Does the recovery inode also have head and tail? Why is a per-inode lock needed during a write?NOVA:radix tree は全 CPU で共有か、ディレクトリごとか。なぜ「128 バイトに整列」なのか。サブテーブルはどう延長するのか。「dequeue を enqueue まで更新」とは何か。16 バイトの「値」とは何か。なぜ read でもページを探すのか。「最大のプール」は空きが最も多いプールか。アロケータのサイズはなぜ変わるのか。recovery inode にも head と tail があるのか。書き込み中になぜ inode ごとのロックが要るのか。
  • 同學報告:vault 的定義;HMC 1.0 是否真的只有 read 與 write;CPU 到 PIM 與 PIM 到 PIM 的延遲是否相同;skip list 的複雜度待查;跨 vault 的負載平衡怎麼做;pipelining 能藏多少時間。Labmates' reports: what a vault is; whether HMC 1.0 really offers only read and write; whether CPU-to-PIM and PIM-to-PIM latency are equal; the skip-list complexity to check; how load balance across vaults is done; how much latency pipelining can hide.同級生の発表:vault の定義。HMC 1.0 は本当に read と write だけか。CPU と PIM 間、PIM と PIM 間のレイテンシは同じか。skip list の計算量は要確認。vault をまたぐ負荷分散はどう行うか。パイプライン化でどれだけレイテンシを隠せるか。
回到頂端 ↑Back to top ↑ページ上部へ ↑

作業系統、RTOS 課程與 Linux 內部機制Operating systems, an RTOS course, and Linux internalsオペレーティングシステム、RTOS 講義、Linux 内部機構

這九則筆記橫跨研究所作業系統課的三週紀錄、一門在 STM32F4 Discovery 上跑 FreeRTOS 的 RTOS 課,以及幾則 Linux 核心的零散問答與待讀連結。作者邊聽邊記,用「??」標出沒聽懂的地方;本節整理記下的事實,並把問號彙整成最後的待解問題。These nine notes span three weeks of a graduate operating-systems course, an RTOS course running FreeRTOS on an STM32F4 Discovery board, and a scatter of Linux-kernel questions and reading links. The author wrote while listening and marked every unclear point with "??"; this section records the captured facts and collects the question marks into a final list of open questions.この九本のノートは、大学院 OS 講義三週分の記録、STM32F4 Discovery 上で FreeRTOS を動かす RTOS 講義、そして Linux カーネルに関する断片的な問答と積読リンクにまたがる。著者は聴きながら書き、わからなかった点を「??」で印した。本節では記録された事実を整理し、疑問符を最後の未解決の問いにまとめる。

研究所作業系統課(9/7、9/14、9/21)Graduate OS course notes (9/7, 9/14, 9/21)大学院 OS 講義ノート(9/7、9/14、9/21)

來源筆記:Source notes: 出典ノート:作業系統筆記.md

9/7 從 key-value storage 與 LevelDB 開場,把作業系統定義為「管理系統的系統」:本質是資源分配者,核心工作是排程,而排程不一定要公平,效率常與公平衝突。早期 OS 叫 monitor,負責記錄程式錯誤。計算理論插曲:不存在能有效率驗證另一支程式正確性的程式,這是停機問題;作者記成「NP-hard?」並寫「NP 代表 non-polynomial」,這不精確(NP 是 nondeterministic polynomial,停機問題是不可判定)。筆記也區分 worst case(最糟輸入)與 average case(依輸入機率加權)。The 9/7 lecture opens with key-value storage and LevelDB, then defines an operating system as "the system that manages the system": a resource allocator whose core job is scheduling, where scheduling need not be fair and efficiency often conflicts with fairness. Early operating systems were called monitors and recorded program errors. A computability aside: no efficient program can verify another program's correctness, which is the halting problem; the author wrote "NP-hard?" and "NP denotes non-polynomial", which is imprecise (NP is nondeterministic polynomial, and the halting problem is undecidable). The note also separates worst case (the worst input) from average case (weighted by input probability).9/7 は key-value ストレージと LevelDB から始まり、OS を「システムを管理するシステム」と定義する。本質は資源割当者で中核はスケジューリングだが、公平である必要はなく、効率はしばしば公平と衝突する。初期の OS は monitor と呼ばれ、プログラムの誤りを記録した。計算理論の脱線:他のプログラムの正しさを効率よく検証するプログラムは存在せず、これが停止問題。著者は「NP-hard?」「NP は non-polynomial」と書いたが不正確だ(NP は nondeterministic polynomial、停止問題は決定不能)。最悪ケース(最悪入力)と平均ケース(入力確率で重み付け)の区別も記されている。

可靠性、可用性與效能是恐龍本沒講的三角:效能理論上是應用端的責任,可靠性是使用時出錯的機率,可用性關乎保養週期;資料庫 delay 拖到 timeout 就是降低可用性。堆疊是 app → middleware → kernel → hardware,順帶提了 FUSE。FLP impossibility:非同步系統模型下沒有演算法能保證存活節點達成共識;Paxos 是一種共識演算法。老師的結論是「scale has been the single most important force driving changes in system software over the last decade」,整堂課在談分散式系統,Hadoop 被稱為分散式作業系統。Reliability, availability and performance form a triangle the dinosaur book skips: performance is in theory the application's responsibility, reliability is the probability of failure in use, availability concerns the maintenance cycle; a database whose delay grows until requests time out is losing availability. The stack is app → middleware → kernel → hardware, with FUSE mentioned in passing. FLP impossibility: in an asynchronous system model no algorithm can guarantee the surviving nodes reach consensus; Paxos is one consensus algorithm. The lecturer's conclusion was that "scale has been the single most important force driving changes in system software over the last decade"; the lecture was really about distributed systems, with Hadoop described as a distributed operating system.信頼性・可用性・性能は恐竜本が飛ばす三角関係だ。性能は理論上アプリケーション側の責任、信頼性は使用中に故障する確率、可用性は保守周期に関わる。データベースの遅延が延びてタイムアウトするのは可用性の低下だ。スタックは app → middleware → kernel → hardware で、FUSE にも触れた。FLP 不可能性:非同期システムモデルでは生き残ったノードの合意を保証するアルゴリズムはない。Paxos は合意アルゴリズムの一つ。講師の結論は「scale has been the single most important force driving changes in system software over the last decade」で、講義は分散システムの話であり、Hadoop は分散 OS と呼ばれた。

9/14 先談中斷與同步、非同步 I/O(後者把 CPU 讓出,完成時以中斷叫回),再談 benchmark 方法論:用什麼指標(GHz、MIPS、MFLOPS)、什麼組態與 workload、怎麼取數據、怎麼彙總比較與報告。SPEC2006 量 CPU 整數與浮點,TPC-C 量資料庫;toy 程式只測單一元件如 cache;結果與輸入資料有關;監控本身會干擾系統,作者比喻為測不準定理(其實是觀察者效應)。幾何平均、調和平均與 Amdahl 定律都打了問號,只記得幾何平均可用對數算。The 9/14 lecture starts with interrupts and synchronous versus asynchronous I/O (the latter gives the CPU away and is called back by an interrupt), then benchmarking methodology: which metrics (GHz, MIPS, MFLOPS), which configuration and workloads, how to obtain data, how to summarise, compare and report. SPEC2006 measures CPU integer and floating point, TPC-C measures databases; toy programs test one component such as the cache; results depend on input data; monitoring itself perturbs the system, which the author likened to the uncertainty principle (really the observer effect). Geometric mean, harmonic mean and Amdahl's law all got question marks, with only the hint that a geometric mean can be computed through logarithms.9/14 はまず割り込みと同期・非同期 I/O(後者は CPU を手放し、完了時に割り込みで呼び戻される)、次にベンチマーク手法。どの指標か(GHz、MIPS、MFLOPS)、どの構成とワークロードか、データをどう取るか、どう要約・比較・報告するか。SPEC2006 は CPU の整数・浮動小数点を、TPC-C はデータベースを測る。toy プログラムは cache など単一部品を試す。結果は入力データに依存する。監視自体がシステムを乱し、著者は不確定性原理に喩えたが実際は観測者効果だ。幾何平均、調和平均、Amdahl の法則は疑問符付きで、幾何平均は対数で計算できるという手がかりだけが残った。

9/21 由助教講作業:外部合併排序。排 100 GB 這種放不進記憶體的資料必須在硬碟排,buffer 滿了倒到檔案;2-way merge 用約三個 buffer,一般化版本 pass 0 用四個 input buffer 產生若干 run,再以某個 fan-out 合併,作者猜「buffer 越多 run 越少」並記下「log 底數越大合併次數越少」。泡沫與插入排序複雜度高、對近乎排好的資料反而糟;堆積排序與 merge sort 適合大資料;Python 用 timsort。工具:free -g 看記憶體,perf 與 perf top 看 pipeline、迴圈與 cache miss 事件,4 KB 對齊是 SSD 的最小單位。作業要同時跑數支程式觀察 OS 切換,10/6 交,重點是效能分析報告。On 9/21 the TA walked through the assignment: external merge sort. Data that does not fit in memory, say 100 GB, must be sorted on disk, spilling each full buffer to a file; a 2-way merge uses about three buffers, the general version uses four input buffers in pass 0 to produce runs that are merged with some fan-out. The author guessed "more buffers, fewer runs" and noted "a larger log base means fewer merge passes". Bubble and insertion sort have high complexity and behave badly on nearly sorted input; heap sort and merge sort suit big data; Python uses timsort. Tools: free -g for memory, perf and perf top for pipeline, loop and cache-miss events, and 4 KB alignment as the SSD's minimum unit. The assignment runs several programs at once to watch the OS switch between them, is due 10/6, and the performance-analysis report is the point.9/21 は TA による課題解説:外部マージソート。100 GB のようにメモリに入らないデータはディスク上でソートし、満杯のバッファをファイルへ流す。2-way マージは約三つのバッファ、一般版は pass 0 で四つの入力バッファから run を作り、ある fan-out でマージする。著者は「バッファが多いほど run は少ない」と推測し「log の底が大きいほどマージ回数が減る」と記した。バブルと挿入は計算量が大きくほぼ整列済みデータに弱い。ヒープソートとマージソートは大規模データ向き。Python は timsort。ツールは free -g でメモリ、perf と perf top で pipeline、ループ、cache miss イベント、4 KB アラインメントは SSD の最小単位。課題は複数プログラムを同時に走らせて OS の切替を観察するもので、締切 10/6、重点は性能分析レポートだ。

作業的重點不是排完,而是解釋快慢的原因:buffer 數與 fan-out 如何決定合併回合、4 KB 對齊如何影響 SSD、perf 的事件如何對應程式行為。The assignment is not about finishing the sort but about explaining why it was fast or slow: how buffer count and fan-out set the number of merge passes, how 4 KB alignment affects the SSD, and how perf events map to program behaviour.課題の肝はソートを終えることではなく、速さ遅さの理由を説明すること。バッファ数と fan-out がマージ回数をどう決め、4 KB アラインメントが SSD にどう効き、perf のイベントがプログラム挙動にどう対応するか。

RTOS 課程:STM32F4 Discovery 上的 FreeRTOSRTOS course: FreeRTOS on the STM32F4 DiscoveryRTOS 講義:STM32F4 Discovery 上の FreeRTOS

來源筆記:Source notes: 出典ノート:rtos課程筆記.md, freeRTOS.md

一學期 RTOS 課的流水帳,夾雜大量連結。開頭三問:同優先權下 FIFO 與 round-robin 差在哪;scheduler 與 context switch 的關係;為什麼用號誌做 critical section 能縮短關中斷時間(只在模擬 test-and-set 的兩行期間關中斷,因為硬體沒有原子的 test-and-set)。3/18:heap_3 先 suspend 排程器再呼叫 malloc;hook 是事件後執行的函式(作者問與 callback 何異);LR 存呼叫後的返回位址;FreeRTOS 是否支援 time slicing。A running log of a semester-long RTOS course, interleaved with many links. Three opening questions: what separates FIFO from round-robin at equal priority; how the scheduler relates to a context switch; and why a semaphore-based critical section shortens the interrupt-off window (interrupts are disabled only around the two lines emulating test-and-set, because the hardware has no atomic test-and-set). From 3/18: heap_3 suspends the scheduler before calling malloc; a hook is a function run after an event (the author asks how that differs from a callback); LR holds the return address after a call; and does FreeRTOS support time slicing.一学期の RTOS 講義の流れを追った記録で、多数のリンクが混じる。冒頭の三問:同一優先度での FIFO と round-robin の違い。スケジューラとコンテキストスイッチの関係。セマフォで critical section を作ると割り込み禁止時間が短くなる理由(ハードウェアに原子的 test-and-set がないため、それを模倣する二行の間だけ割り込みを切る)。3/18:heap_3 は malloc の前にスケジューラを suspend する。hook はイベント後に実行される関数(著者は callback との違いを問う)。LR は呼出し後の戻り先を保持する。FreeRTOS は time slicing を支援するか。

3/25 進入 Cortex-M 細節:main stack 與 process stack 分別給 OS 與任務,handler 預設用 main stack,PSP 是 process stack pointer;context switch 在 SVC handler 裡做,r2 指向目前 TCB;BASEPRI 設定哪些優先權的中斷可進入;ISB flush pipeline;有些 CPU 的 vector table 可搬動。Kernel 有兩個優先權,平常一個、進 critical section 後拉到另一個。不呼叫 FreeRTOS API 的 ISR 用任何優先權都可以(作者問為什麼);FromISR 系列不會 block,因為 ISR 不是任務實體、沒有 TCB 存狀態;recursive mutex 是什麼也打了問號。The 3/25 lecture went into Cortex-M detail: the main stack and process stack serve the OS and the tasks, handlers use the main stack by default and PSP is the process stack pointer; the context switch happens inside the SVC handler with r2 pointing at the current TCB; BASEPRI sets which interrupt priorities may enter; ISB flushes the pipeline; on some CPUs the vector table can be relocated. The kernel has two priority levels, one for normal use and one it raises itself to inside a critical section. An ISR that calls no FreeRTOS API may use any priority (the author asks why); the FromISR APIs never block because an ISR is not a task entity and has no TCB to save state in; "what is a recursive mutex" is another question mark.3/25 は Cortex-M の詳細へ。main stack と process stack はそれぞれ OS とタスク用で、ハンドラは既定で main stack を使い、PSP は process stack pointer。コンテキストスイッチは SVC handler 内で行われ、r2 が現在の TCB を指す。BASEPRI はどの優先度の割り込みを受け付けるかを決め、ISB はパイプラインをフラッシュし、CPU によってはベクタテーブルを移動できる。カーネルには二つの優先度があり、通常用と critical section 内で引き上げる用。FreeRTOS API を呼ばない ISR はどの優先度でもよい(著者はなぜかと問う)。FromISR 系はブロックしない。ISR はタスク実体でなく状態を保存する TCB がないからだ。「recursive mutex とは何か」も疑問符付き。

4/15 與 4/29 談 IPC。計數號誌記錄未處理事件數或限制資源取用量;新版把 task notification 從一個數字擴充成陣列;notification 可當輕量版 event group,但只能「任一 bit 就喚醒」,做不到「全部 bit 才喚醒」。stream buffer 建立在 notification 上;message buffer 每則長度可不同,並能在 sbSEND_COMPLETED() 裡產生中斷把另一個核心叫起來收資料。vTaskSuspendAll 關掉排程器。專門的 timer task 執行 timer callback,可操作號誌但不建議呼叫會 block 的函式;也記了 one-shot timer 與用 timer id 傳資料。記憶體保護只在 MPU port 實作:堆疊不可讀寫但可執行,受保護 region 在 context switch 時換掉,否則數量不夠。The 4/15 and 4/29 lectures covered IPC. A counting semaphore records pending events or caps how many times a resource is taken; newer FreeRTOS extends task notifications from one value to an array; a notification can act as a lightweight event group, but only in "wake on any bit" form, never "wake only when all bits are set". Stream buffers are built on notifications; message buffers carry variable-length messages and can wake another core to receive data by generating an interrupt inside sbSEND_COMPLETED(). vTaskSuspendAll turns the scheduler off. A dedicated timer task runs the timer callbacks, where semaphores are allowed but blocking calls are discouraged; one-shot timers and passing data through the timer id were noted too. Memory protection exists only in MPU ports: the stack is no-read, no-write but executable, and the protected regions are swapped at each context switch because there are not enough of them.4/15 と 4/29 は IPC。カウンティングセマフォは未処理イベント数を記録するか資源の取得回数を制限する。新しい FreeRTOS はタスク通知を単一値から配列に拡張した。通知は軽量版イベントグループとして使えるが「いずれかのビットで起こす」だけで「すべて揃ったときだけ起こす」はできない。ストリームバッファは通知の上に作られ、メッセージバッファは可変長メッセージを運び、sbSEND_COMPLETED() 内で割り込みを生成して別コアを起こしデータを受け取らせられる。vTaskSuspendAll はスケジューラを止める。専用の timer task がタイマーのコールバックを実行し、セマフォは使えるがブロックする呼出しは推奨されない。one-shot タイマーと timer id によるデータ受け渡しも記された。メモリ保護は MPU ポートのみで、スタックは読み書き不可だが実行可能、保護 region はコンテキストスイッチごとに差し替える。数が足りないからだ。

老師用 uC/OS-II 作對照。Critical section 內不可 sleep 或 block;實作方式有三種,各有陷阱:直接關中斷,離開時可能無法回復進入前的狀態;把中斷狀態存在堆疊,但會動到 stack pointer、編譯器不知情;用區域變數存狀態。除了 idle task 還有一個統計 task,優先權是最低減一;64 個優先權所以最多 64 個任務;TCB free list 是全域資源,初始化要用 critical section 保護;就緒表以 x、y 索引,掃描從 8×8 降為 8+8;scheduler lock 關掉排程器避免 race condition,前提是 ISR 不會來亂。The lecturer used uC/OS-II as a contrast. Nothing in a critical section may sleep or block; there are three ways to implement one, each with a trap: disabling interrupts outright may fail to restore the pre-entry state; saving the interrupt state on the stack moves the stack pointer behind the compiler's back; or keeping the state in a local variable. Besides the idle task there is a statistics task at the lowest priority minus one; 64 priority levels mean at most 64 tasks; the TCB free list is a global resource that initialisation must protect with a critical section; the ready table is indexed by x and y, cutting the scan from 8×8 to 8+8; and a scheduler lock disables the scheduler to avoid races, assuming ISRs do not interfere.講師は対比として uC/OS-II を取り上げた。critical section 内では sleep もブロックも禁止。実装は三通りで各々罠がある。割り込みを直接切ると元の状態へ戻せないことがある。割り込み状態をスタックに保存するとコンパイラの知らぬ間にスタックポインタが動く。ローカル変数に状態を保存する。idle task のほかに統計タスクがあり優先度は最低マイナス一。優先度 64 段階なのでタスクも最大 64。TCB フリーリストはグローバル資源で初期化時に critical section で保護する。レディテーブルは x、y で索引され走査は 8×8 から 8+8 へ。scheduler lock はレース回避のためスケジューラを止めるが、ISR が邪魔しないことが前提だ。

實作紀錄散在各處。SD 卡走 SPI 跑 FatFs 加 DMA 的範例來自 CSDN 與 ST 的 middleware;多任務共用 FatFs 時作者找到 FreeRTOS 論壇「FatFs 只在 taskENTER_CRITICAL 裡才正常」的討論串,通常表示 SPI 驅動不是執行緒安全、需要 mutex。I2S DAC wave player 參考 controllerstech 的 Discovery 範例;雜音原先懷疑是 clock 設定,交叉測試後確定是 WAV 格式問題。Timer 中斷的教訓:初始化後中斷旗標未清,一開中斷就直接進處理函式,必須先清旗標;用到 HAL_TIM_PeriodElapsedCallback、HAL_TIM_Base_Start_IT、HAL_TIM_Base_Stop_IT。其他連結涵蓋 C 記憶體佈局(bss)、Cortex-M 中斷優先權與 FreeRTOS 的對應、FatFs 函式原型、RCC 說明、STM32F407 Discovery 電路圖與 NCKU 嵌入式課程的 FreeRTOS wiki。freeRTOS.md 只有「老師的投影片心得紀錄」一個標題。The practical records are scattered. SD card over SPI with FatFs and DMA came from CSDN articles and ST's middleware; for tasks sharing FatFs the author found the FreeRTOS forum thread "FatFs works only with taskENTER_CRITICAL", which usually means the SPI driver is not thread-safe and needs a mutex. The I2S DAC wave player followed the controllerstech Discovery example; the noise was first blamed on a clock setting, but cross-testing traced it to the WAV format. The timer-interrupt lesson: the interrupt flag is not cleared after initialisation, so the handler fires the moment the interrupt is enabled, and the flag must be cleared first; the HAL functions are HAL_TIM_PeriodElapsedCallback, HAL_TIM_Base_Start_IT and HAL_TIM_Base_Stop_IT. Other links cover the C memory layout (bss), how Cortex-M interrupt priorities map onto FreeRTOS, FatFs prototypes, an RCC explainer, the STM32F407 Discovery schematic and the NCKU embedded-course FreeRTOS wiki. freeRTOS.md holds only the heading "notes on the lecturer's slides".実装記録は散在している。SPI 経由の SD カードで FatFs と DMA を使う例は CSDN 記事と ST のミドルウェアから。タスクが FatFs を共有する件では FreeRTOS フォーラムの「FatFs は taskENTER_CRITICAL の中でしか動かない」スレッドを見つけた。通常 SPI ドライバがスレッドセーフでなく mutex が要ることを意味する。I2S DAC の wave player は controllerstech の Discovery 例に従い、ノイズは最初クロック設定が疑われたが相互テストで WAV 形式が原因と判明した。タイマー割り込みの教訓:初期化後に割り込みフラグが消えず、有効化した瞬間にハンドラへ入るため、先にフラグを消す。HAL 関数は HAL_TIM_PeriodElapsedCallback、HAL_TIM_Base_Start_IT、HAL_TIM_Base_Stop_IT。その他のリンクは C のメモリ配置(bss)、Cortex-M 割り込み優先度と FreeRTOS の対応、FatFs プロトタイプ、RCC 解説、STM32F407 Discovery 回路図、NCKU 組込み講義の FreeRTOS wiki。freeRTOS.md は「講師スライドの所感」という見出しだけだ。

Cortex-M 上的 FreeRTOS 有兩條硬規則:呼叫 FreeRTOS API 的 ISR 優先權必須在 configMAX_SYSCALL_INTERRUPT_PRIORITY 之內且只用 FromISR 版本;timer 初始化後要先清旗標再開中斷,否則第一次中斷立刻假觸發。FreeRTOS on Cortex-M has two hard rules: an ISR that calls any FreeRTOS API must sit at or below configMAX_SYSCALL_INTERRUPT_PRIORITY and use only FromISR variants; and a timer's flag must be cleared after initialisation before enabling the interrupt, or the first interrupt fires spuriously at once.Cortex-M 上の FreeRTOS には二つの硬い規則がある。FreeRTOS API を呼ぶ ISR は configMAX_SYSCALL_INTERRUPT_PRIORITY 以下に置き FromISR 版だけを使う。タイマーは初期化後、割り込み有効化の前にフラグを消す。さもないと最初の割り込みが即座に誤発火する。

Linux 內部機制問答(ChatGPT 回答的筆記)Linux internals Q&A (the ChatGPT-answered note)Linux 内部機構の問答(ChatGPT が答えたノート)

來源筆記:Source notes: 出典ノート:problem answered by chatgpt.md

這則筆記原封不動貼了四段 ChatGPT 回答,作者沒有加註,顯然當成參考答案。第一題宣稱 Linux 有兩個排程器:行程用 CFS,核心執行緒與中斷處理用「Round Robin Scheduler」。這是錯的:核心沒有專給核心執行緒的 round-robin 排程器,核心執行緒和一般行程由同一個排程器依排程類別處理,SCHED_RR 只是任何任務都可設定的即時策略,中斷處理函式根本不經排程。第二題的 EPT(Intel)與 NPT(AMD)描述幾乎逐字相同,大意正確:兩者都是硬體第二層分頁,把客體實體位址轉成主機實體位址、省掉 shadow page table;但「虛擬機不經主機 OS 直接存取主機記憶體」太粗糙,那張表仍由 hypervisor 掌控。第三、四題正確:訊號不是系統呼叫而是 IPC 機制,kill() 才是系統呼叫,核心負責判斷收件行程、投遞、預設行為與 handler API。This note pastes four ChatGPT answers verbatim with no commentary; the author clearly kept them as reference answers. The first claims Linux has two schedulers: CFS for processes and a "Round Robin Scheduler" for kernel threads and interrupt handlers. That is wrong: there is no separate round-robin scheduler for kernel threads, they go through the same scheduler as everything else according to their scheduling class, SCHED_RR is merely a real-time policy any task can be given, and interrupt handlers are not scheduled at all. The second describes Intel's EPT and AMD's NPT in nearly identical words; the gist is right, both are hardware second-level paging that translates guest-physical to host-physical addresses and removes shadow page tables, but "the VM accesses host memory directly without the host OS" is too loose, since the hypervisor still owns that table. The third and fourth are correct: a signal is not a syscall but an IPC mechanism, kill() is the actual syscall, and the kernel picks the recipient, delivers the signal, defines default actions and provides the handler APIs.このノートは ChatGPT の回答四段をそのまま貼り、注釈はない。参考解答として保存したのだろう。第一は Linux に二つのスケジューラがあると主張する。プロセス用の CFS と、カーネルスレッドと割り込みハンドラ用の「Round Robin Scheduler」。これは誤りだ。カーネルスレッド専用の round-robin スケジューラはなく、他と同じスケジューラがスケジューリングクラスに従って扱う。SCHED_RR はどのタスクにも設定できるリアルタイムポリシーにすぎず、割り込みハンドラはそもそもスケジュールされない。第二は Intel の EPT と AMD の NPT をほぼ同じ文で説明する。要旨は正しく、どちらもゲスト物理をホスト物理に変換するハードウェア二段ページングで shadow page table を不要にするが、「VM がホスト OS を経由せずホストメモリに直接アクセスする」は粗すぎる。そのテーブルはハイパーバイザが握っている。第三・第四は正しい。シグナルはシステムコールではなく IPC 機構、kill() が実際のシステムコールで、カーネルが受信先を決め、配送し、既定動作を定め、ハンドラ API を提供する。

epoll 與 I/O 多工epoll and I/O multiplexingepoll と I/O 多重化

來源筆記:Source notes: 出典ノート:epoll system call.md

連結收集加幾句理解。連結有 SegmentFault 的 epoll 入門、Medium 的 The method to epoll's madness(標註「原理,應該是好文」)、一篇 getaddrinfo() 與 socket 入門,以及一篇談 blocking、non-blocking、同步與非同步 I/O model 的中文文章。作者問「epoll_wait 是會 block 的同步函式?目的是什麼?」,自答:epoll 監看一群 socket,任一有資料就立刻返回,歸類為 I/O multiplexing;單一 socket 時沒有優勢,優勢在 socket 很多時。這是對的,可補一句:epoll 不是輪詢,核心在 socket 就緒時把它放進就緒清單,成本不隨監看數線性成長,這正是它勝過 select/poll 之處。更新的 io_uring 在別的筆記出現過,這裡沒提。A link collection with a few sentences of understanding. The links: a SegmentFault epoll primer, The method to epoll's madness on Medium (annotated "the principle, probably a good read"), a getaddrinfo() and socket primer, and a Chinese article on blocking, non-blocking, synchronous and asynchronous I/O models. The author asks "epoll_wait is a blocking synchronous call? what is it for?" and answers: epoll watches a set of sockets and returns as soon as any has data, it is classed as I/O multiplexing, and it has no advantage with a single socket, only when sockets become numerous. That is right, with one refinement: epoll does not poll; the kernel puts a socket on a ready list when it becomes ready, so cost does not grow linearly with the number watched, which is where it beats select and poll. The newer io_uring appears in another note but not here.リンク集に数行の理解を添えたもの。リンクは SegmentFault の epoll 入門、Medium の The method to epoll's madness(「原理、たぶん良記事」と注記)、getaddrinfo() とソケットの入門、blocking・non-blocking・同期・非同期 I/O モデルを論じる中国語記事。著者は「epoll_wait はブロックする同期関数か?目的は何か?」と問い、自答する。epoll はソケット群を監視しどれかにデータが来れば即座に返る。I/O multiplexing に分類され、ソケット一つでは利点がなく、多数のときに利点が出る。これは正しいが一点補える。epoll はポーリングしない。カーネルはソケットが ready になった時点で ready リストに入れるため、コストは監視数に線形に増えない。これが select や poll に勝る点だ。より新しい io_uring は別のノートに現れるがここでは触れていない。

自幹 CPU 與作業系統Build your own CPU and OS自作 CPU と自作 OS

來源筆記:Source notes: 出典ノート:自幹系列文章.md, linux bsp and cpu and porting.md, nuttx.md, freeRTOS.md

四則短筆記都是書籤。自幹系列文章.md 與 linux bsp and cpu and porting.md 重複收了同一組「自己動手寫 CPU」資源:GitHub 的 DIY_OpenMIPS(跟著同名書實作的 OpenMIPS 核)、該書作者的 CSDN 專欄,以及一個經 Facebook 轉址的電子書站連結(不收錄)。「自己動手幹 OS 相關」只有標題;後者標題提到 Linux BSP 與移植,但沒留下任何 BSP 連結。nuttx.md 只有一篇 Medium 文章,介紹在 QEMU 與 VS Code 裡建 NuttX(POSIX 相容的嵌入式 RTOS)開發環境;freeRTOS.md 只有標題。作者顯然想從 RTOS 課往下延伸到 CPU 設計與 OS 移植,但這條線沒有繼續。All four short notes are bookmarks. 自幹系列文章.md and linux bsp and cpu and porting.md collect the same "write your own CPU" set twice: DIY_OpenMIPS on GitHub (an OpenMIPS core built by following the book of that name), the book author's CSDN column, and an e-book site reached through a Facebook redirect, not reproduced. "Write your own OS" is a bare heading; the second file's title mentions Linux BSP and porting but no BSP link was ever added. nuttx.md holds one Medium article on setting up NuttX (a POSIX-compatible embedded RTOS) under QEMU with VS Code; freeRTOS.md is a heading only. The intent was clearly to extend the RTOS course downward into CPU design and OS porting, but the thread was not followed up.四本の短いノートはすべてブックマークだ。自幹系列文章.md と linux bsp and cpu and porting.md は同じ「自分で CPU を書く」資料を二重に集める。GitHub の DIY_OpenMIPS(同名書籍に沿って実装した OpenMIPS コア)、著者の CSDN コラム、Facebook 転送経由の電子書籍サイト(載せない)。「自作 OS 関連」は見出しだけ。後者のタイトルは Linux BSP と移植に触れるが BSP リンクは一つもない。nuttx.md は Medium 記事一本で、NuttX(POSIX 互換の組込み RTOS)を QEMU と VS Code で開発する環境構築。freeRTOS.md は見出しのみ。RTOS 講義から CPU 設計と OS 移植へ掘り下げる意図は明らかだが、この線は続かなかった。

待看文件The to-read list積読リスト

來源筆記:Source notes: 出典ノート:待看文件.md

三個項目。第一是談 gdb 底層系統呼叫 ptrace 的文章(blog.linux.org.tw)。第二是一位 OS 老師的系列影片,作者提出三問:關中斷的區段 gdb 無能為力,但 OS 跑在虛擬機上就能停住,怎麼做到?STM32 上的 FreeRTOS 也只有在 QEMU 裡才能在 kernel 中停住?不用 -O0 的話程式碼可能亂序而妨礙 debug。前兩問的答案:模擬器本身就是除錯器,暫停的是整顆虛擬 CPU,不需要目標上的中斷協助;真機上 JTAG/SWD 的硬體中斷點也能做到,做不到的只是靠中斷的 gdb stub。第三是一篇從硬體觀點解釋 store buffer、invalidate queue 與 memory barrier 的 Medium 文章,與本資料夾的 MESI 筆記呼應。Three items. First, an article on ptrace, the syscall under gdb (blog.linux.org.tw). Second, an OS lecturer's video series, from which the author raised three questions: gdb is helpless where interrupts are disabled, yet an OS in a virtual machine can be stopped there, how? Can FreeRTOS on STM32 likewise only be halted inside the kernel under QEMU? And without -O0 the code may be reordered and hinder debugging. The answer to the first two: the emulator is the debugger, it pauses the whole virtual CPU and needs no cooperation from interrupts on the target; hardware breakpoints over JTAG/SWD do the same on real silicon, only an interrupt-driven gdb stub cannot. Third, a Medium article explaining store buffers, invalidate queues and memory barriers from the hardware's point of view, which pairs with the MESI note elsewhere in this folder.三項目。第一は gdb の下のシステムコール ptrace の記事(blog.linux.org.tw)。第二はある OS 講師の動画シリーズで、著者は三つの疑問を立てた。割り込み無効区間では gdb は無力だが仮想マシン上の OS なら止められる、どうやって?STM32 上の FreeRTOS も QEMU 内でしかカーネルで止められないのか?-O0 を使わないとコードが並べ替えられデバッグの妨げになる。前二問の答え:エミュレータ自体がデバッガで仮想 CPU 全体を止めるので、ターゲット側の割り込みの協力は要らない。実機でも JTAG/SWD のハードウェアブレークポイントで同じことができ、できないのは割り込みに頼る gdb stub だけだ。第三は store buffer、invalidate queue、memory barrier をハードウェア観点で説明する Medium 記事で、このフォルダの MESI ノートと対になる。

待解問題Open questions未解決の問い

來源筆記:Source notes: 出典ノート:作業系統筆記.md, rtos課程筆記.md, epoll system call.md, 待看文件.md

  • 幾何平均與調和平均各適用哪種 benchmark 指標?Amdahl 定律怎麼用在作業的效能分析?外部合併排序中 buffer 數、run 數與 fan-out 的精確關係?Which benchmark metrics call for a geometric mean and which for a harmonic mean? How does Amdahl's law enter the assignment's analysis? What is the exact relation between buffer count, runs and fan-out in external merge sort?幾何平均と調和平均はそれぞれどのベンチマーク指標に使うのか。Amdahl の法則は課題の分析でどう使うのか。外部マージソートでバッファ数、run 数、fan-out の正確な関係は何か。
  • 為什麼不呼叫 FreeRTOS API 的 ISR 可以用任何優先權?hook 與 callback 差在哪?recursive mutex 是什麼?heap_x 是在任務裡被呼叫的嗎?Why may an ISR that calls no FreeRTOS API use any priority? What separates a hook from a callback? What is a recursive mutex? Is heap_x called from inside a task?FreeRTOS API を呼ばない ISR はなぜどの優先度でもよいのか。hook と callback は何が違うのか。recursive mutex とは何か。heap_x はタスク内から呼ばれるのか。
  • 多個任務共用 FatFs 時,除了整段包在 taskENTER_CRITICAL 裡,正確做法是什麼?When several tasks share FatFs, what is the correct approach other than wrapping everything in taskENTER_CRITICAL?複数タスクが FatFs を共有するとき、全体を taskENTER_CRITICAL で包む以外の正しい方法は何か。
  • epoll_wait 既然會 block,它與同步 I/O 的界線在哪?在 QEMU 裡能停在關中斷的 kernel 區段,真機上的替代方案是什麼?Since epoll_wait blocks, where is the line between it and synchronous I/O? If QEMU can halt inside an interrupts-off kernel region, what is the equivalent on real hardware?epoll_wait がブロックするなら同期 I/O との境界はどこか。QEMU では割り込み禁止のカーネル区間で止められるが、実機での代替手段は何か。
回到頂端 ↑Back to top ↑ページ上部へ ↑

第八節:C 語言閱讀清單、MATLAB、投影片範本、外包案規格與個人規劃Section 8: C reading list, MATLAB, a slide template, freelance scoping and personal planning第8節:C言語の読書リスト、MATLAB、スライドテンプレート、外注案件の仕様検討と個人の計画メモ

本節收攏匯出中的零散筆記:C 語言書籤清單、MATLAB 速查、HackMD 內建投影片範本、兩份標「外包案」的規格討論,以及資格考與工作日誌的規劃筆記。都不是完成的文章,而是閱讀、估價與排程時留下的原始材料。This section gathers the loose ends of the export: a C bookmark list, a MATLAB refresher, HackMD's stock slide template, two scoping notes tagged 外包案 (freelance), and planning notes for a qualifying exam and a work log. None is a finished write-up; they are the raw material of reading, estimating and scheduling.本節はエクスポートの端切れをまとめる。C言語のブックマーク一覧、MATLAB復習、HackMD標準のスライドテンプレート、「外包案」(外注案件)タグ付きの仕様検討ノート2本、資格試験と作業日誌の計画メモである。どれも完成した文章ではなく、読み、見積もり、予定を組む際の素材である。

C 語言閱讀清單:從指標到 eBPFThe C reading list: from pointers to eBPFC言語の読書リスト:ポインタからeBPFまで

來源筆記:Source notes: 出典ノート:c語言好文.md

c語言好文.md 是依主題編號的連結清單。指標一項只有一篇部落格文。資料結構一項指向解析 libuv 佇列的文章,作者留下整份筆記唯一真正的疑問:元素之間似乎至少隔 16 bytes,猜是兩個 8 bytes 指標的距離。猜對了:libuv 的 queue 是侵入式雙向鏈結串列,每個節點內嵌 next 與 prev 指標,64 位元下這對指標正是 16 bytes。c語言好文.md is a numbered list of links by topic. The pointer entry is one blog post. The data-structure entry is a walkthrough of libuv's queue, where the author left the note's one real puzzle: elements seem at least 16 bytes apart, guessed to be two 8-byte pointers. The guess is right: libuv's queue is an intrusive doubly linked list, each node embeds next and prev pointers, and on 64-bit that pair is 16 bytes.c語言好文.md はテーマ別に番号を振ったリンク一覧である。ポインタの項はブログ記事1本。データ構造の項はlibuvのキュー解説で、ノート唯一の本当の疑問が残る。要素間が少なくとも16バイト離れて見える、8バイトのポインタ2本分ではないか、という推測だ。推測は正しい。libuvのキューは侵入型の双方向連結リストで、各ノードにnextとprevのポインタが埋め込まれ、64ビットではその対が16バイトになる。

其餘像一份低階 C 的課綱:lvalue 與 rvalue、GCC 的 C 語言擴充、資料對齊(songho.ca)、「10 分鐘讀懂 linker script」、thread pool 筆記、開啟編譯器特殊功能、hash table 範例、臺師大演算法筆記的圖與圖走訪。兩條加重的提醒:priority queue 用 heap 實作「查!!」,以及 quick sort。The rest reads like a syllabus for low-level C: lvalue versus rvalue, GCC's C extensions, data alignment (songho.ca), a ten-minute guide to linker scripts, a thread-pool note, enabling special compiler features, a worked hash table, and NTNU's page on graphs and traversal. Two emphatic reminders: implement a priority queue with a heap ("look it up!!"), and quicksort.残りは低レベルCのシラバスのようだ。lvalueとrvalue、GCCのC拡張、データアライメント(songho.ca)、「10分で読めるリンカスクリプト」、スレッドプールの覚書、コンパイラ特殊機能の有効化、ハッシュテーブルの実例、台湾師範大学のグラフとグラフ走査のページ。強調された備忘が2つ、優先度付きキューはヒープで実装「調べろ!!」、そしてクイックソートである。

筆記貼了一段 Linux 核心課程講高效能 Web 伺服器的文字,說明長期連線的兩種失敗:瀏覽器關閉時 read 回傳 0,伺服器呼叫 close 即可;客戶端網路離線時協定無從得知,只能靠 timer。timer 放在以 binary heap 實作的 priority queue,從開頭即可找到逾時連線。另一做法是睡到最近的 timer 到期為止,稱為 tickless,通常以階層式 timing wheel 實作。A pasted paragraph from a Linux kernel course on high-performance web servers explains two failures of a long-lived connection: when the browser closes, read returns 0 and the server just calls close; when the client's network drops, the protocol cannot tell, so timers are needed. Timers go in a priority queue on a binary heap, so expired connections sit at the head. The alternative is to sleep exactly until the nearest timer expires, called tickless and usually built on a hierarchical timing wheel.貼られたLinuxカーネル講座の高性能Webサーバーの一節は、長期接続の2つの失敗を説明する。ブラウザが閉じれば read が0を返しサーバーは close を呼ぶだけでよいが、クライアントのネットワークが切れるとプロトコルには分からず、タイマーが要る。タイマーはバイナリヒープ上の優先度付きキューに置き、先頭を見れば期限切れの接続が見つかる。もう一つは最も近いタイマーの期限までちょうど眠る方法で、ticklessと呼ばれ通常は階層型タイミングホイールで作る。

之後是零散書籤:User-mode Linux 環境、課程測驗、不用分支而用 bitwise 比較大小、eBPF 課程頁(列兩次,第二次標「作業」)、只有關鍵字的「mysql 原理」、sem_timedwait、架構圖的 C4 model、學生自幹 OS 的討論串、成大嵌入式課程的 rtenv wiki。Then scattered bookmarks: a User-mode Linux environment, a course quiz, branchless min/max with bitwise operations, the eBPF course page (listed twice, once as "homework"), the bare keyword "mysql internals", sem_timedwait, the C4 model for architecture diagrams, a thread on students building their own OS, and NCKU's embedded-course rtenv wiki.その後は散発的なブックマークである。User-mode Linux環境、講座の小テスト、分岐なしのbitwise演算による大小比較、eBPF講座ページ(2回、1回は「宿題」)、キーワードだけの「mysqlの原理」、sem_timedwait、アーキテクチャ図のC4モデル、学生の自作OSのスレッド、成功大学組込み講座のrtenv wiki。

int (*func[5])(int *p);

最長的評論是對上面宣告的逐步解析:[] 優先順序高於 *,所以 func 先與 [5] 結合,是五個元素的陣列;* 修飾的是 func[5] 而非 func,所以元素是指標;跳出括號看 (int *p),每個指標指向以 int * 為參數、回傳 int 的函式。接著三個連結示範用以狀態為索引的函式指標表實作有限狀態機。The longest commentary parses the declaration above step by step: [] binds tighter than *, so func first joins [5] and is an array of five; the * modifies func[5], not func, so the elements are pointers; outside the parentheses, (int *p) says each points to a function taking int * and returning int. Three links then show a finite state machine built as a table of function pointers indexed by state.最も長い解説は上の宣言の段階的な解析である。[] は * より優先順位が高いので func はまず [5] と結合して5要素の配列になり、* は func ではなく func[5] を修飾するので要素はポインタ、括弧の外の (int *p) から各ポインタは int * を取り int を返す関数を指す。続く3つのリンクは状態を添字とする関数ポインタ表による有限状態機械を示す。

另一段貼文解釋 __THROW:只存在於 Linux 的 C 函式庫,在 C 裡沒有作用,只有標頭被 C++ 引用時才宣告該函式可能拋出例外。「mysql 原理」與 quick sort 未展開,是待辦。Another passage explains __THROW: it exists only in the Linux C library, does nothing in C, and only when included from C++ declares that the function may throw. "mysql internals" and quicksort stay open.別の貼り付け文は __THROW を説明する。LinuxのCライブラリにしかなく、Cでは何もせず、C++から取り込まれたときだけ関数が例外をthrowしうると宣言する。「mysqlの原理」とクイックソートは未展開のままである。

MATLAB 速查:元素運算、冒號與 numelMATLAB refresher: element-wise operators, the colon and numelMATLAB復習:要素ごとの演算、コロン記法とnumel

來源筆記:Source notes: 出典ノート:matlab.md

matlab.md 只記三件事。第一,./ 與 .* 是逐元素的除法與乘法,與矩陣運算子不同。第二,冒號記法與 end:matlab.md records three facts. First, ./ and .* are element-wise division and multiplication, unlike the matrix operators. Second, colon notation with end:matlab.md は3つの事実だけを記す。第一に ./ と .* は要素ごとの除算と乗算で、行列演算子とは異なる。第二に end を伴うコロン記法:

arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12]
arr4(2:end, 2:end)

ans =
     6     7     8
    10    11    12

2:end 是從第二個到最後一個,所以取的是第二列到最後一列、第二行到最後一行。第三,numel(A) 回傳元素個數,影像則為像素數,另有 numel(A, 條件) 形式。四張 imgur 截圖示範冒號、逗號與分號的角色與 numel 範例,此處不重製。2:end means second to last, so the call takes rows two to last and columns two to last. Third, numel(A) returns the element count, the pixel count for an image, with a numel(A, condition) form. Four imgur screenshots showed the roles of colon, comma and semicolon and numel examples; they are not reproduced.2:end は2番目から最後までで、2行目から最終行、2列目から最終列を取る。第三に numel(A) は要素数、画像なら画素数を返し、numel(A, 条件) 形式もある。imgurの4枚はコロン、カンマ、セミコロンの役割とnumelの例を示していたが再掲しない。

Talk slides template:HackMD 的內建投影片範本Talk slides template: HackMD's stock slide deckTalk slides template:HackMD標準のスライドテンプレート

來源筆記:Source notes: 出典ノート:Talk slides template.md

Talk slides template.md 是 HackMD 自帶的「Talk」範本,不是作者的內容。它仍是 Slide Mode 的語法備忘:front-matter 放 title、tags、description;單獨一行 --- 分隔投影片;{%youtube ID %} 嵌入影片;graphviz 區塊直接畫成圖(範例是「Hackmd-it core」透過 sync 節點與 HackMD 編輯器及 GitHub、GitLab 來源雙向同步的 rankdir=RL 圖);<style> 區塊把 code.blue 與 code.orange 染色;以及 emoji 短碼。Talk slides template.md is HackMD's own "Talk" template, not the author's content. It still serves as a Slide Mode cheat sheet: front-matter with title, tags and description; --- alone on a line between slides; {%youtube ID %} for a video; a graphviz block rendered as a diagram (the example is a rankdir=RL graph where "Hackmd-it core" syncs both ways, via a sync node, with the HackMD editor and GitHub or GitLab sources); a <style> block colouring code.blue and code.orange; and emoji shortcodes.Talk slides template.md はHackMD自身の「Talk」テンプレートで作者の内容ではない。それでもSlide Modeの文法メモになる。title、tags、descriptionのfront-matter、スライドを区切る1行だけの ---、動画の {%youtube ID %}、図として描画される graphviz ブロック(例は「Hackmd-it core」がsyncノードを介してHackMDエディタとGitHubやGitLabのソースと双方向同期するrankdir=RLのグラフ)、code.blue と code.orange を着色する <style> ブロック、絵文字ショートコードである。

範本的敘事是瀏覽器擴充套件架構:content script 綁定每個頁面,在隔離的 JavaScript 環境操作 DOM。TypeScript 片段示範 Channeru 通道函式庫:Channeru.create() 建立通道,背景腳本用 channel.answer('isLogin', …) 回應,注入腳本用 await channel.callBackground('isLogin') 得到 true。The deck's narrative is a browser-extension architecture: a content script bound to each page, manipulating the DOM in an isolated JavaScript environment. The TypeScript snippets show a channel library called Channeru: Channeru.create() sets up the channel, the background script answers with channel.answer('isLogin', …), and the inject script gets true from await channel.callBackground('isLogin').デッキの筋書きはブラウザ拡張のアーキテクチャで、各ページに結び付くcontent scriptが隔離されたJavaScript環境でDOMを操作する。TypeScriptの断片はChanneruというチャネルライブラリを示す。Channeru.create() でチャネルを作り、background scriptは channel.answer('isLogin', …) で応答し、inject scriptは await channel.callBackground('isLogin') でtrueを得る。

外包案 A:「呼叫師傅」派工服務的軟體規格Freelance case A: software for a "call a technician" dispatch service外注案件A:「師傅を呼ぶ」派遣サービスのソフトウェア仕様

來源筆記:Source notes: 出典ノート:呼叫師傅 軟體規格討論.md

呼叫師傅 軟體規格討論.md 是與一位經營到府維修派工服務的業主開規格會議的議程。項目有:CRM;LINE 整合(粗體標「第一優先」);Excel VBA 實作的會計系統;與客戶及師傅溝通的 SOP;派工時間表與通知客戶施工時間;Excel VBA 的資料存取;主機放哪裡。呼叫師傅 軟體規格討論.md is the agenda for a scoping meeting with a client who runs a home-repair dispatch service. The items: a CRM; LINE integration, bolded as "the first priority"; accounting in Excel VBA; SOPs for talking to customers and technicians; a dispatch timetable with customer notifications; Excel VBA data access; and hosting.呼叫師傅 軟體規格討論.md は出張修理の派遣サービスを営む依頼主との仕様打ち合わせの議題である。項目はCRM、LINE連携(太字で「最優先」)、Excel VBAの会計システム、顧客と技術者との連絡SOP、顧客通知付きの派遣予定表、Excel VBAのデータアクセス、ホスティング先。

LINE 一項最具體:自動化靠 Windows 桌面自動化工具(筆記連到一篇開源工具整理),LINE 跑在 Windows guest VM 裡。紅字問題:業主原本的 LINE 還能用嗎?機器人是否需要另一個 LINE 身分,因而多一個手機門號,一支便宜的 Android 手機夠不夠?Excel VBA 能否連 MongoDB?紅字答「可以」,引 StackOverflow;MySQL 是否較易實作,沒有結論。最後問業主電腦能否 24 小時開機,可以就用 VirtualBox 架伺服器:Windows host,Windows 與 Linux guest。The LINE item is the most concrete: automation relies on a Windows desktop automation tool (the note links a survey of open-source ones), with LINE in a Windows guest VM. In red: can the client's existing LINE keep working, or does the bot need its own LINE identity and so a second phone number, which a cheap Android phone could supply? Can Excel VBA reach MongoDB? Red answer: yes, citing StackOverflow; whether MySQL is easier is left open. Finally, can the client's PC stay on 24 h? If so, the server runs in VirtualBox on it: Windows host, Windows and Linux guests.LINEの項目が最も具体的で、自動化はWindowsデスクトップ自動化ツール(オープンソースツールのまとめ記事にリンク)に頼り、LINEはWindowsゲストVMで動かす。赤字の疑問は、依頼主の既存のLINEは使い続けられるか、ボットに別のLINE IDが要り、ゆえに2つ目の携帯番号が必要で、安いAndroid端末で足りるか。Excel VBAはMongoDBに届くか、赤字で「できる」とStackOverflowを引く。MySQLの方が楽かは未解決。最後に依頼主のPCは24時間稼働できるか、できればその上のVirtualBoxにサーバーを置く、ホストはWindows、ゲストはWindowsとLinux。

外包案 B:太陽能儲能公司的電流感測與 FOC 問題Freelance case B: current sensing and FOC questions for a solar and energy-storage company外注案件B:太陽光・蓄電会社の電流計測とFOCの問い

來源筆記:Source notes: 出典ノート:太陽能儲能公司.md

太陽能儲能公司.md 的題目是「電流感測值的累積與縮放」。第一問:什麼感測器、怎麼運作?貼了分合式電流互感器(split-core CT)的說明:鐵芯可打開扣上導體,安裝不必中斷電流;一次側電流在鐵磁鐵芯產生磁場,在二次繞組感應出成比例的電流供監測裝置讀取。太陽能儲能公司.md is about "current sensor value accumulation and scale-down". First question: what sensor, and how does it work? A pasted explanation of split-core current transformers: the core opens and clamps around the conductor, so installation never interrupts the current; the primary current magnetises a ferromagnetic core and induces a proportional current in the secondary winding for a monitoring device to read.太陽能儲能公司.md の課題は「電流センサ値の累積とスケールダウン」。最初の問いは、どんなセンサでどう動くか。分割型変流器(split-core CT)の説明が貼られている。鉄心が開いて導体を挟むので電流を止めずに取り付けられ、一次電流が強磁性の鉄心を磁化して二次巻線に比例する電流を誘導し、監視装置に読ませる。

第二問是電路:一顆運算放大器夠嗎,還是要微控制器?數字:一次側 100 A 時 CT 二次側 50 mA = 0.05 A,接 100 Ω 得 5 V。截圖的整流有二極體 0.7 V 壓降問題,於是貼上蕭特基二極體說明:一般二極體壓降 0.7–1.7 V,蕭特基只有 0.15–0.45 V,紅字「可能替代一般 diode?」。待辦:PCB layout 工具、該買哪些晶片、先用洞洞板做原型。工時:12/15 討論 1 小時、查電路 2 小時。代辦:請業主量街燈內阻;孤立的 20.3 Ω 寫在只有標題的「simple company website design」項下,顯然是量測結果。Second question, the circuit: is one op-amp enough, or is a microcontroller needed? The numbers: at 100 A primary the CT gives 50 mA = 0.05 A, which across 100 Ω is 5 V. The screenshot's rectifier suffers the 0.7 V diode drop, so the note pastes the Schottky description: an ordinary diode drops 0.7 to 1.7 V, a Schottky only 0.15 to 0.45 V, with the red remark "a possible replacement for the ordinary diode?". Open items: a PCB layout tool, which chips to buy, a protoboard prototype first. Hours: 12/15, discussion 1 h, circuit search 2 h. To-do: ask the client to measure the street light's internal resistance; a lone 20.3 Ω under the heading-only item "simple company website design" is evidently that result.2番目の問いは回路で、オペアンプ1個で足りるかマイコンが要るか。数値は、一次側100 AでCT二次側は50 mA = 0.05 A、100 Ωで5 V。スクリーンショットの整流はダイオードの0.7 V降下に悩むので、ショットキーの説明を貼る。通常のダイオードは0.7〜1.7 V、ショットキーは0.15〜0.45 Vで、赤字に「通常のダイオードの代替になりうる?」。残る項目はPCBレイアウトツール、買うチップ、まずユニバーサル基板で試作。工数は12/15、打ち合わせ1時間、回路調査2時間。やることは依頼主に街灯の内部抵抗を測ってもらうこと。見出しだけの「simple company website design」の下の20.3 Ωがその結果と見られる。

筆記尾端換題:FOC 馬達控制。貼了感應馬達轉子磁通位置的量測方法:位置感測器(霍爾、解角器、編碼器);馬達電流特徵分析(MCSA);需要定子電阻與轉子時間常數的模型估測;以及判讀電壓電流波形的「馬達示波器」。文末建議諮詢馬達廠或合格電機工程師。The tail switches to FOC motor control, pasting ways to measure an induction motor's rotor flux position: a position sensor (Hall, resolver, encoder); motor current signature analysis (MCSA); model-based estimation needing stator resistance and rotor time constant; and a "motor oscilloscope" reading voltage and current waveforms. It ends by advising a motor manufacturer or qualified electrical engineer.末尾はFOCモータ制御に話題を変え、誘導電動機の回転子磁束位置の測定法を貼る。位置センサ(ホール、レゾルバ、エンコーダ)、モータ電流特徴解析(MCSA)、固定子抵抗と回転子時定数を要するモデルベース推定、電圧と電流の波形を読む「モータオシロスコープ」。文章はモータメーカーか有資格の電気技術者に相談せよと締める。

個人規劃:資格考、工作日誌與一個汽車音響連結Personal planning: the qualifying exam, the work log and a car-audio link個人の計画:資格試験、作業日誌、カーオーディオのリンク

來源筆記:Source notes: 出典ノート:資格考.md, 工作日誌.md, 汽車音響.md

資格考.md 幾乎是空的:計算機組織一節記「參考書目是第四版」,下面是兩位同學的名字與分享的雲端資料夾(略去);作業系統只有標題。汽車音響.md 只有一個汽車音響部落格連結,沒有評語。資格考.md is nearly empty: the computer-organisation section says "the reference textbook is the fourth edition", followed by two classmates' names and shared drive folders (dropped); the operating-systems section is a bare heading. 汽車音響.md is one car-audio blog link with no comment.資格考.md はほぼ空で、計算機構成の節に「参考書は第4版」とあり、同級生2人の名前と共有ドライブ(省略)が続く。オペレーティングシステムは見出しだけ。汽車音響.md はカーオーディオのブログ記事へのリンク1本でコメントはない。

工作日誌.md 較有內容。「每天都要找時間做的」:作業系統與計算機組織資格考、「fuzzy or VLSI??」、讀論文、核心課程作業(打問號)、minix 教科書。「非每天」是有日期的檢查表,劃掉的有:另一分割區的 mkfs(8/31)、學長的論文(8/31)、幫他做投影片(接近完成)、DMA coherence(9/1)、NOVA 論文(9/6)、IEEE 754 與二補數 bitwise 練習、列印 PMFS 論文、從 GitHub 建置 NOVA(9/10)。工作日誌.md has more substance. "Find time every day": the OS and computer-organisation quals, "fuzzy or VLSI??", papers, the kernel course's homework (question-marked), the minix textbook. "Not every day" is a dated checklist. Struck through: mkfs for another partition (8/31), a senior labmate's paper (8/31), slides for him (almost), DMA coherence (9/1), the NOVA paper (9/6), the IEEE 754 two's-complement bitwise exercise, printing the PMFS paper, building NOVA from GitHub (9/10).工作日誌.md はもう少し中身がある。「毎日時間を見つけてやること」はOSと計算機構成の資格試験、「fuzzy or VLSI??」、論文、カーネル講座の宿題(疑問符付き)、minixの教科書。「毎日ではないこと」は日付入りチェックリストで、取り消し済みは別パーティションのmkfs(8/31)、先輩の論文(8/31)、そのスライド(ほぼ完成)、DMA coherence(9/1)、NOVA論文(9/6)、IEEE 754と2の補数のbitwise演習、PMFS論文の印刷、GitHubからのNOVAビルド(9/10)。

未完成的:在 QEMU 的 STM32 上追蹤 FreeRTOS;gem5 SMP 當機實驗(classic 與 Ruby MOESI directory);紅字的運管 SDK 與追蹤同學的程式碼;radix tree(prefix tree 的一種);記憶體控制器文件;OS benchmark;hook function;user-space 檔案系統論文;紅字「追蹤 NOVA 核心模組:做 QEMU 映像檔,用 scp 放入 .ko」;worker thread 實作練習;計畫書撰寫:三年內容(第一年可寫學長的工作)、related works 參考學長文獻與上期計畫書、老師的投影片、博士面試時老師給的計畫書格式。Pending: trace FreeRTOS on QEMU's STM32; the gem5 SMP crash experiments (classic and Ruby MOESI directory); in red, a transport-authority SDK and tracing a labmate's code; radix tree (a kind of prefix tree); a memory-controller document; an OS benchmark; hook functions; a user-space file-system paper; in red, "trace the NOVA kernel module: build a QEMU image and scp the .ko in"; a worker-thread exercise; and the research proposal: three years of content (year one can describe the senior labmate's work), related works from his bibliography and the previous proposal, the advisor's slides, and the proposal format the advisor handed over at the PhD interview.未完了は、QEMUのSTM32上でFreeRTOSを追う、gem5のSMPクラッシュ実験(classicとRuby MOESI directory)、赤字の交通管理SDKと同級生のコード追跡、radix tree(prefix treeの一種)、メモリコントローラ文書、OSベンチマーク、hook function、ユーザー空間ファイルシステムの論文、赤字の「NOVAカーネルモジュールを追う:QEMUイメージを作り.koをscpで入れる」、ワーカースレッド練習、そして研究計画書。3年分の内容(1年目は先輩の成果を書ける)、related worksは先輩の文献と前期の計画書、指導教員のスライド、博士面接時に指導教員が渡した計画書の形式に倣う。

重點整理Takeaways要点

來源筆記:Source notes: 出典ノート:c語言好文.md, 呼叫師傅 軟體規格討論.md, 太陽能儲能公司.md, 工作日誌.md

C 清單最值得留下的三件事:libuv 佇列的 16 bytes 步距就是一對 8 bytes 指標;int (*func[5])(int *p) 要從優先順序較高的 [] 先讀;長期連線的逾時靠 binary heap 上的 priority queue,或 tickless 的 timing wheel。Three things to keep from the C list: the 16-byte stride in libuv's queue is one pair of 8-byte pointers; read int (*func[5])(int *p) from the higher-precedence [] first; and timeouts on long-lived connections need a priority queue on a binary heap, or a tickless timing wheel.Cの一覧から残す3点:libuvキューの16バイトのストライドは8バイトポインタ1対分、int (*func[5])(int *p) は優先順位の高い [] から読む、長期接続のタイムアウトにはバイナリヒープ上の優先度付きキューかticklessのタイミングホイールが要る。

兩份外包案筆記示範了便宜的範圍界定:先排需求的優先順序(LINE 第一),把每個技術風險寫成問句(第二個 LINE 身分?MongoDB 還是 MySQL?電腦能 24 小時開著嗎?),並記錄工時。儲能案的硬體結論很小但具體:100 A → 50 mA → 100 Ω 上的 5 V,0.7 V 壓降用蕭特基解決。The two freelance notes show cheap scoping done well: rank the wants (LINE first), turn each technical risk into a question (a second LINE identity? MongoDB or MySQL? can the PC stay on 24 h?), and log the hours. The energy-storage case ends with a small but concrete result: 100 A becomes 50 mA becomes 5 V across 100 Ω, and the 0.7 V drop is answered with a Schottky.2本の外注ノートは安上がりで良いスコーピングの手本である。要望に優先順位を付け(LINEが最初)、技術的リスクを問いに変え(2つ目のLINE ID?MongoDBかMySQLか?PCは24時間稼働できるか?)、工数を記録する。蓄電案件は小さいが具体的な結論で終わる。100 Aが50 mAになり100 Ω上で5 V、0.7 Vの降下にはショットキーで応える。

回到頂端 ↑Back to top ↑ページ上部へ ↑

全部 42 篇筆記索引Index of all 42 notes全 42 ノートの索引

下表列出匯出中的每一篇筆記。欄位依序為:流水號、檔名、主題、HackMD 標籤(無標籤者標示「無」)、檔案大小(KB,1 KB = 1024 位元組,取一位小數)、一句話摘要。筆記先依七個主題分組,同一主題內再依大小由大到小排列;主題的順序和本頁各章相同,因此可以把這張表當作本頁的目錄來用。The table lists every note in the export. The columns are: a running number, the filename, the theme, the HackMD tags (or none), the file size in KB (1 KB = 1024 bytes, one decimal), and a one-sentence gist. Notes are grouped into the seven themes used by this page and, inside each theme, ordered from the largest file to the smallest. The themes follow the order of the sections above, so the table doubles as a map of the page.下の表はエクスポートに含まれる全ノートを並べたものだ。列は順に、通し番号、ファイル名、テーマ、HackMD のタグ(タグなしは「なし」)、ファイルサイズ(KB、1 KB = 1024 バイト、小数一桁)、一文の要旨である。ノートは本ページと同じ七つのテーマに分け、同じテーマの中ではサイズの大きい順に並べた。テーマの並びは上の各節と同じなので、この表はページの地図としても使える。

#筆記Noteノート主題Themeテーマ標籤Tagsタグ大小 (KB)Size (KB)サイズ (KB)摘要Gist要旨
1姿態估計.md慣性感測Inertial sensing慣性センシング訊號處理10.8以陀螺儀與加速規做姿態估計:四元數微分、旋轉矩陣、把機體加速度投影到絕對座標系,以及機體與慣性座標系角速度的關係。Attitude estimation from gyro and accelerometer: quaternion differentiation, rotation matrices, projecting body acceleration into the world frame, and body versus inertial angular rates.ジャイロと加速度計による姿勢推定:四元数の微分、回転行列、機体加速度の絶対座標系への投影、機体系と慣性系の角速度の関係。
2ahrs.md慣性感測Inertial sensing慣性センシング訊號處理6.1以 Mahony 濾波器為核心的 AHRS 學習筆記:尤拉角與四元數旋轉的等價、修正迴路的 PID 觀點、x-IMU 程式片段與磁力計參考連結。AHRS study notes around the Mahony filter: Euler versus quaternion rotation, a PID view of the correction loop, x-IMU code fragments, and magnetometer links.Mahony フィルタを中心とした AHRS の学習ノート:オイラー角と四元数回転の等価性、補正ループの PID 的見方、x-IMU のコード断片、磁力計の参考リンク。
3kalman filter.md慣性感測Inertial sensing慣性センシング訊號處理3.0卡爾曼濾波器的連結整理:公式推導、必背的五條方程式、MATLAB 程式、MPU-6050 筆記,以及互補濾波為何要融合加速規與陀螺儀。A link collection on the Kalman filter: derivation, the five update equations, MATLAB code, an MPU-6050 write-up, and why complementary filtering fuses accel and gyro.カルマンフィルタのリンク集:式の導出、暗記すべき五つの更新式、MATLAB コード、MPU-6050 の記事、相補フィルタが加速度計とジャイロを融合する理由。
4位移計算.md慣性感測Inertial sensing慣性センシング訊號處理2.6由加速度求位移:ST 的重力扣除應用筆記、|a| 約為 1 g 時將速度歸零的 ZVU、以及扣除積分漂移的 MATLAB 片段。Displacement from acceleration: the ST app note on gravity subtraction, zero-velocity updates that reset velocity when |a| is 1 g, and a drift-removal MATLAB snippet.加速度から変位を求める:ST の重力除去アプリケーションノート、|a| が 1 g のとき速度をリセットする ZVU、積分ドリフトを除く MATLAB の断片。
5四元數.md慣性感測Inertial sensing慣性センシング訊號處理2.0IMU 用的四元數基礎:旋轉參考文章、由陀螺儀資料求四元數變化率、重力補償的連結,以及一段簡短的 Python 旋轉範例。Quaternion basics for IMU work: rotation references, the quaternion rate from gyro data, gravity compensation links, and a small Python rotation example.IMU 向けの四元数の基礎:回転の参考記事、ジャイロから求める四元数の変化率、重力補償のリンク、短い Python の回転例。
6邊坡種子.md邊坡種子Slope seed斜面センサー種子會議記錄41.4埋入式邊坡感測「種子」計畫七個月的會議紀錄:提案、廠商參訪、與土木系合作的振動台試驗、STM32 與 LoRa 設定、演算法討論與經費。Seven months of meeting minutes for the buried slope-sensor project: proposals, vendor visits, shake-table tests with civil engineering, STM32 and LoRa setup, algorithms, and budget.埋設型斜面センサー「種子」計画の七か月分の議事録:提案、ベンダー訪問、土木系との振動台試験、STM32 と LoRa の設定、アルゴリズム、予算。
7lora.md邊坡種子Slope seed斜面センサー種子訊號處理0.4關於 LoRa 閘道器與 MQTT broker 的三個待解問題:多閘道器會否重複收到同一節點資料、休眠秒數需大於 10 秒、訂閱端在另一台機器時是否改走乙太網路。Three open questions about the LoRa gateway and MQTT broker: duplicate uplinks across gateways, a sleep interval above ten seconds, and reaching the broker over Ethernet.LoRa ゲートウェイと MQTT ブローカーに関する三つの未解決の疑問:複数ゲートウェイでの重複受信、10 秒を超えるスリープ間隔、別マシンのブローカーへ有線で届くか。
8智慧交通的code.md智慧交通Smart transportスマート交通無noneなし46.6最大的一篇:RSU 中介軟體原始碼閱讀(事件迴圈、UDP)、每日會議與路測紀錄、TSP 與 EVSP 新功能追蹤,以及各路口的疑難排解。The largest note: RSU middleware source reading (event loop, UDP), daily meeting and field-test logs, new-feature tracking for TSP and EVSP, and intersection troubleshooting.最大のノート:RSU ミドルウェアのソース読解(イベントループ、UDP)、日々の会議と路上試験の記録、TSP と EVSP の新機能追跡、交差点ごとのトラブル対応。
9智慧運輸.md智慧交通Smart transportスマート交通會議記錄3.1V2X 軟體堆疊的會議紀錄:是否繞過 Unex 的 V2Xcast API、ZeroMQ 的 request-reply 與 pub-sub、各埠的用途,以及執行緒與 IPC 的待解問題。Meeting notes on the V2X stack: whether to bypass the Unex V2Xcast API, ZeroMQ request-reply and pub-sub sockets, port roles, and open questions on threads and IPC.V2X スタックの会議メモ:Unex の V2Xcast API を迂回するか、ZeroMQ の request-reply と pub-sub、ポートの役割、スレッドと IPC に関する未解決の疑問。
10致翰交接.md智慧交通Smart transportスマート交通無noneなし1.1接手 RSU 中介軟體的交接筆記:callback 執行順序、DSRC 的 dispatcher id、每台車一個 OBU 物件,另附一次實驗室會議關於 OTA 參數與時程的討論。Handover notes from the labmate who owned the RSU middleware: callback ordering, DSRC dispatcher id, one OBU object per vehicle, plus a lab meeting on OTA parameters and deadlines.RSU ミドルウェア担当者からの引き継ぎメモ:コールバックの実行順、DSRC の dispatcher id、車両ごとの OBU オブジェクト、OTA パラメータと期限を扱った研究室会議。
11rsu checklist.md智慧交通Smart transportスマート交通無noneなし0.8RSU 路測實驗前後的檢查清單:資料庫 id、in-service 旗標、GPS 位置、TSP 與 EVSP 啟用狀態、時制計畫檔名,以及事後恢復行人倒數。A before-and-after checklist for RSU field experiments: database ids, in-service flag, GPS position, TSP and EVSP enable flags, plan names, and restoring the pedestrian countdown.RSU 路上実験の前後チェックリスト:DB の id、in-service フラグ、GPS 位置、TSP と EVSP の有効化、プラン名の一致、実験後の歩行者カウントダウン復旧。
12交接文件格式.md智慧交通Smart transportスマート交通無noneなし0.3三篇關於如何寫好交接文件的書籤文章,其中一篇被標註為最接近需求。Three bookmarked articles on how to write a good handover document, with one of them marked as the closest fit.良い引き継ぎ文書の書き方に関する三本のブックマーク記事、うち一本を最も近いと注記。
13mesi protocol(也稱為伊利諾斯協議,是因為該協議由伊利諾斯州立大學提出).md架構與並行Architecture and concurrencyアーキテクチャと並行性無noneなし3.6從多張狀態圖整理 MESI 快取一致性:四種狀態、BusRdX 與 BusUpgr、write-back 與 write-through 的差別,以及 S→S 為何有兩種事件。MESI cache coherence worked through from several diagrams: the four states, BusRdX and BusUpgr, write-back versus write-through, and why S-to-S appears twice.複数の状態図から MESI キャッシュ一貫性を整理:四つの状態、BusRdX と BusUpgr、ライトバックとライトスルーの違い、S→S 遷移が二種類ある理由。
14dma cache coherence.md架構與並行Architecture and concurrencyアーキテクチャと並行性無noneなし3.0DMA 與快取一致性:不快取的緩衝區、裝置到記憶體前先 invalidate、記憶體到裝置前先 clean,以及 DMA 緩衝區為何必須對齊 cache line。DMA and cache coherence: uncached buffers, invalidate before device-to-memory and clean before memory-to-device, and why DMA buffers must be cache-line aligned.DMA とキャッシュ一貫性:非キャッシュバッファ、デバイスからメモリの前の invalidate とメモリからデバイスの前の clean、DMA バッファがキャッシュライン境界に揃う必要がある理由。
15計算機結構筆記.md架構與並行Architecture and concurrencyアーキテクチャと並行性無noneなし1.4計算機結構課的零碎筆記:VLIW、領域專用架構、IEEE 754 的邊角案例、bfloat16、捨入模式、Kahan 求和與記憶體配置策略。Lecture scraps from a computer architecture course: VLIW, domain-specific architectures, IEEE 754 corner cases, bfloat16, rounding modes, Kahan summation, and memory allocation strategies.計算機構造の授業の断片メモ:VLIW、ドメイン特化アーキテクチャ、IEEE 754 の端ケース、bfloat16、丸めモード、Kahan 加算、メモリ割り当て戦略。
16同步.md架構與並行Architecture and concurrencyアーキテクチャと並行性無noneなし0.8sem_init 的原型、pshared 對執行緒與行程的意義,以及「號誌初值為 0 的目的是什麼」這個待解問題。The sem_init prototype, what pshared means for threads versus processes, and an open question about why a semaphore would start at zero.sem_init のプロトタイプ、pshared がスレッド間とプロセス間で持つ意味、初期値 0 のセマフォは何のためかという未解決の疑問。
17concurrency and parallism_ 並行和多執行緒程式設計 (上).md架構與並行Architecture and concurrencyアーキテクチャと並行性無noneなし0.5並行程式設計的一句話重點:號誌早於互斥鎖、超純量的廣度與管線的深度、超執行緒其實共用 ALU、per-CPU 資料,以及沒有作業系統也有可重入問題。One-line takeaways on concurrency: semaphores before mutexes, superscalar width versus pipeline depth, hyper-threading as shared ALUs, per-CPU data, and reentrancy without an OS.並行処理の一行メモ:セマフォはミューテックスより先、スーパースカラの幅とパイプラインの深さ、ALU を共有するハイパースレッディング、per-CPU データ、OS なしでも起こる再入問題。
18continous runahead_ transparent hardware acceleration for memory intensive workloads.md架構與並行Architecture and concurrencyアーキテクチャと並行性paper0.5Continuous Runahead 論文的關鍵字:runahead 執行、GHB 與 stream 預取器、位於記憶體控制器的共用加速引擎,以及約 70% 的預取涵蓋率。Keywords from the Continuous Runahead paper: runahead execution, GHB and stream prefetchers, a shared engine at the memory controller, and prefetch coverage near 70 percent.Continuous Runahead 論文のキーワード:runahead 実行、GHB と stream プリフェッチャ、メモリコントローラに置く共有エンジン、約 70% のプリフェッチ到達率。
19資料結構與演算法.md架構與並行Architecture and concurrencyアーキテクチャと並行性無noneなし0.4紅黑樹與 radix tree 的連結整理,包含 Linux page cache 如何使用 radix tree 的一篇文章。Links on red-black trees and radix trees, including an article on how the Linux page cache is built on a radix tree.赤黒木と radix tree のリンク整理で、Linux のページキャッシュが radix tree を使う仕組みの記事を含む。
20rcu related;lock free.md架構與並行Architecture and concurrencyアーキテクチャと並行性無noneなし0.4RCU 與 lock-free 的閱讀連結,加上一句 rwlock 規則:讀者之間不互斥,但寫者與任何人都互斥。RCU and lock-free reading links plus a one-line rwlock rule: readers do not exclude readers, but writers exclude everyone.RCU とロックフリーの読み物リンクに加え、rwlock の一行ルール:読者同士は排他しないが書き手は全員と排他する。
21pipeline.md架構與並行Architecture and concurrencyアーキテクチャと並行性無noneなし0.3兩張管線示意圖與華盛頓大學管線課程講義的連結,附一句關於記憶體讀取階段的說明。Two pipeline diagrams and a link to a University of Washington pipelining lecture, with one sentence on the memory-read stage.パイプラインの図二枚とワシントン大学のパイプライン講義へのリンク、メモリ読み出し段についての一言。
22NOVA file system.mdPIM 與 NVM 論文PIM and NVM papersPIM・NVM 論文paper pim12.6逐節閱讀 NOVA 非揮發性記憶體檔案系統:每個 inode 一份 log、DRAM 中的 radix tree 索引、輕量 journal、資料採 copy-on-write、寫入順序與垃圾回收。A section-by-section reading of the NOVA NVMM file system: per-inode logs, DRAM radix indexes, lightweight journaling, copy-on-write data, write ordering, and garbage collection.NOVA NVMM ファイルシステムの節ごとの読解:inode ごとのログ、DRAM 上の radix tree 索引、軽量ジャーナル、コピーオンライトのデータ、書き込み順序、ガベージコレクション。
23a processing-in-memory architecture programming paradigm for wireless IOT applications.mdPIM 與 NVM 論文PIM and NVM papersPIM・NVM 論文paper pim8.4物聯網 PIM 程式設計範式論文的閱讀筆記:循序執行的 ARM 主機、無作業系統的 PIM 核心、不快取的共用緩衝區、內建於 PIM 的 DMA,以及 gem5 與 FPGA 評估。Reading notes on a PIM programming paradigm for IoT: in-order ARM host, OS-less PIM cores, uncached shared buffers, a DMA inside the PIM, and gem5 plus FPGA evaluation.IoT 向け PIM プログラミング方式の論文メモ:インオーダー ARM ホスト、OS なしの PIM コア、非キャッシュ共有バッファ、PIM 内蔵 DMA、gem5 と FPGA による評価。
24一些linux file system的屬性.mdPIM 與 NVM 論文PIM and NVM papersPIM・NVM 論文無noneなし2.2轉錄的 atime、ctime、mtime 教學,附一段 shell script 與四個分鐘級實驗,說明哪種操作會更新哪個時間戳記。A copied tutorial on atime, ctime and mtime with a shell script and four timed experiments showing which operations touch which timestamp.atime・ctime・mtime の解説の転記で、シェルスクリプトと四つの時間差実験からどの操作がどのタイムスタンプを更新するかを示す。
25paper report of others.mdPIM 與 NVM 論文PIM and NVM papersPIM・NVM 論文無noneなし1.6聽兩位同學報告論文的筆記:近記憶體運算的並行資料結構,以及 2017 年 PIM 綜述中的快閃寫入放大、PCM 與 MRAM。Notes from two labmates' paper talks: concurrent data structures for near-memory computing, and a 2017 PIM survey covering flash write amplification, PCM, and MRAM.研究室メンバー二人の論文発表メモ:ニアメモリ計算向け並行データ構造、フラッシュの書き込み増幅・PCM・MRAM を扱う 2017 年の PIM サーベイ。
26rtos課程筆記.md作業系統、RTOS 與 LinuxOS, RTOS and LinuxOS・RTOS・Linux課程6.7RTOS 課程筆記:排程疑問、Cortex-M 中斷優先權、FreeRTOS 的 heap 方案、SPI SD 卡上的 FatFS、I2S DAC 音訊、記憶體保護與 uC/OS-II。An RTOS course notebook: scheduler questions, Cortex-M interrupt priorities, FreeRTOS heap schemes, FatFS over SPI SD cards, I2S DAC audio, memory protection, and uC/OS-II.RTOS 授業ノート:スケジューラの疑問、Cortex-M の割り込み優先度、FreeRTOS のヒープ方式、SPI SD カード上の FatFS、I2S DAC 音声、メモリ保護、uC/OS-II。
27作業系統筆記.md作業系統、RTOS 與 LinuxOS, RTOS and LinuxOS・RTOS・Linux無noneなし4.5研究所作業系統課堂筆記:效率的定義、停機問題、可靠性與可用性、FLP 不可能定理、Paxos、中斷、效能評測與外部合併排序。Graduate OS lecture notes: what efficiency means, the halting problem, reliability versus availability, FLP impossibility, Paxos, interrupts, benchmarks, and external merge sort.大学院 OS 講義ノート:効率の定義、停止問題、信頼性と可用性、FLP 不可能性、Paxos、割り込み、ベンチマーク、外部マージソート。
28problem answered by chatgpt.md作業系統、RTOS 與 LinuxOS, RTOS and LinuxOS・RTOS・Linuxlinux related3.4四個 Linux 問題與聊天機器人的回答:CFS 與核心排程、Intel EPT 與 AMD NPT、signal 是否為系統呼叫;內容需自行查證。Four Linux questions pasted with chatbot answers: CFS versus the kernel scheduler, Intel EPT and AMD NPT, and whether signals are system calls. Treat with care.Linux の四つの質問とチャットボットの回答:CFS とカーネルスケジューラ、Intel EPT と AMD NPT、シグナルはシステムコールか。鵜呑みにしないこと。
29epoll system call.md作業系統、RTOS 與 LinuxOS, RTOS and LinuxOS・RTOS・Linux無noneなし0.8關於 epoll 與 I/O 模型的文章,加上作者自己的理解:socket 數量很多時 epoll 才有優勢。Articles on epoll and I/O models, with the author's own understanding that epoll shines only when the socket count grows large.epoll と I/O モデルの記事、そしてソケット数が多いときにこそ epoll が有利という自分なりの理解。
30待看文件.md作業系統、RTOS 與 LinuxOS, RTOS and LinuxOS・RTOS・Linux無noneなし0.7待讀清單:gdb 用的 ptrace、一套作業系統影片及其「中斷關閉時能否在 QEMU 中停住」的疑問,以及 store buffer 與記憶體屏障。A reading queue: ptrace for gdb, an OS video series with questions on debugging inside disabled interrupts under QEMU, and store buffers and memory barriers.読む予定のリスト:gdb の ptrace、OS 動画シリーズと割り込み禁止区間を QEMU で止められるかという疑問、ストアバッファとメモリバリア。
31linux bsp and cpu and porting.md作業系統、RTOS 與 LinuxOS, RTOS and LinuxOS・RTOS・Linux無noneなし0.7兩個自製 CPU 的連結:OpenMIPS 專案與一本自己動手寫 CPU 的書,歸在 BSP 與移植之下。Two links toward building your own CPU: an OpenMIPS repository and a book on writing a CPU, filed under BSP and porting.自作 CPU に向けた二つのリンク:OpenMIPS リポジトリと CPU 自作本、BSP と移植の項目に分類。
32自幹系列文章.md作業系統、RTOS 與 LinuxOS, RTOS and LinuxOS・RTOS・Linux無noneなし0.4自幹系列的書籤:自己動手寫 CPU(OpenMIPS、部落格專欄、一本書)以及自己寫作業系統的占位標題。Bookmarks for the do-it-yourself series: writing a CPU (OpenMIPS, a blog column, a book) and a placeholder heading for writing an OS.自作シリーズのブックマーク:CPU を自作する(OpenMIPS、ブログ連載、書籍)と、OS 自作のための見出しだけの項目。
33nuttx.md作業系統、RTOS 與 LinuxOS, RTOS and LinuxOS・RTOS・Linuxrtos0.2僅一個連結:以 QEMU 與 VS Code 建立 NuttX 開發環境、做 POSIX 嵌入式系統的 Medium 文章。A single link to a Medium article on setting up NuttX with QEMU and VS Code for POSIX embedded development.QEMU と VS Code で NuttX 環境を構築し POSIX 組み込み開発をする Medium 記事へのリンク一つのみ。
34freeRTOS.md作業系統、RTOS 與 LinuxOS, RTOS and LinuxOS・RTOS・Linuxrtos0.1掛在 rtos 標籤下的空白筆記,只有「老師的投影片心得紀錄」一個標題,沒有任何內容。An empty stub under the rtos tag, holding only a heading for impressions of the instructor's slides and nothing else.rtos タグの空のノートで、講師スライドの感想という見出しがあるだけで中身はない。
35太陽能儲能公司.mdC、MATLAB、工具、外包與規劃C, MATLAB, tools, freelance and planningC・MATLAB・ツール・外注・計画外包案4.9太陽能儲能客戶的外包筆記:開口式電流互感器、100 A 轉 50 mA 的縮放電路、用蕭特基二極體避開 0.7 V 壓降,以及 FOC 轉子位置量測。Freelance notes for a solar storage client: split-core current transformers, a 100 A to 50 mA scaling circuit, Schottky diodes to dodge the 0.7 V drop, and FOC rotor position.太陽光蓄電クライアントの外注メモ:分割コア CT、100 A を 50 mA に落とす回路、0.7 V 降下を避けるショットキーダイオード、FOC の回転子位置。
36c語言好文.mdC、MATLAB、工具、外包與規劃C, MATLAB, tools, freelance and planningC・MATLAB・ツール・外注・計画無noneなし4.2精選 C 語言文章:指標、佇列、lvalue、GCC 擴充、對齊、linker script、執行緒池、雜湊表、圖論、tickless 計時器、eBPF 與函式指標陣列。Curated C articles: pointers, queues, lvalues, GCC extensions, alignment, linker scripts, thread pools, hash tables, graphs, tickless timers, eBPF, and function pointer arrays.厳選した C 言語記事:ポインタ、キュー、lvalue、GCC 拡張、アラインメント、リンカスクリプト、スレッドプール、ハッシュ表、グラフ、tickless タイマー、eBPF、関数ポインタ配列。
37Talk slides template.mdC、MATLAB、工具、外包與規劃C, MATLAB, tools, freelance and planningC・MATLAB・ツール・外注・計画Templates Talk2.4HackMD 內建的演講投影片範本,未經修改:slide mode 的 front matter、範例章節、一張 graphviz 圖與表情符號標題。HackMD's stock talk-slide template, untouched: slide-mode front matter, sample sections, a graphviz diagram, and emoji headings.HackMD 標準のトークスライドテンプレートそのまま:slide mode の front matter、サンプル節、graphviz 図、絵文字の見出し。
38工作日誌.mdC、MATLAB、工具、外包與規劃C, MATLAB, tools, freelance and planningC・MATLAB・ツール・外注・計画無noneなし1.4個人待辦日誌:每日資格考複習、讀論文、gem5 SMP 當機、在 QEMU 中追 NOVA 核心模組,以及撰寫三年期計畫書。A personal to-do log: daily qualifying-exam study, paper reading, gem5 SMP crashes, NOVA kernel module tracing in QEMU, and drafting a three-year proposal.個人の ToDo 日誌:毎日の資格試験勉強、論文読み、gem5 SMP のクラッシュ、QEMU での NOVA カーネルモジュール追跡、三年計画書の執筆。
39呼叫師傅 軟體規格討論.mdC、MATLAB、工具、外包與規劃C, MATLAB, tools, freelance and planningC・MATLAB・ツール・外注・計画外包案1.2呼叫師傅外包案的需求討論:LINE 自動化優先、Excel VBA 會計、連接 MongoDB 或 MySQL,以及在客戶電腦上架設伺服器。Scoping a freelance job for a repair-dispatch business: LINE automation first, Excel VBA accounting, MongoDB or MySQL access, and hosting on the client's own PC.修理手配業向け外注案件の要件整理:LINE 自動化を最優先、Excel VBA 会計、MongoDB か MySQL への接続、顧客 PC 上でのサーバー運用。
40matlab.mdC、MATLAB、工具、外包與規劃C, MATLAB, tools, freelance and planningC・MATLAB・ツール・外注・計画無noneなし0.8MATLAB 複習:逐元素的 ./ 與 .*、搭配 end 的冒號切片,以及 numel,各附小陣列範例。MATLAB refreshers: elementwise ./ and .*, colon slicing with end, and numel, each illustrated with a small array example.MATLAB の復習:要素ごとの ./ と .*、end を使うコロン切り出し、numel、それぞれ小さな配列の例つき。
41資格考.mdC、MATLAB、工具、外包與規劃C, MATLAB, tools, freelance and planningC・MATLAB・ツール・外注・計画資格考0.3資格考準備:計算機組織採用第四版教科書、兩位同學分享的雲端資料夾,作業系統部分仍為空白。Qualifying exam prep: computer organization uses the fourth edition textbook, shared drive folders from two classmates, and an operating systems section still empty.資格試験の準備:計算機組織は第四版教科書、同級生二人の共有フォルダ、OS の節はまだ空欄。
42汽車音響.mdC、MATLAB、工具、外包與規劃C, MATLAB, tools, freelance and planningC・MATLAB・ツール・外注・計画無noneなし0.1整份匯出中最小的一篇:只有一個汽車音響安裝的部落格書籤,其餘未寫任何內容。The smallest note in the export: one bookmarked blog post about car audio installation, with nothing else written.エクスポート中で最小のノート:カーオーディオ取り付けのブログをブックマークしただけで、他には何も書かれていない。

合計:42 篇筆記,共 191,093 位元組(約 186.6 KB)。其中 19 篇帶有 HackMD 標籤,23 篇沒有標籤。最大的兩篇是 智慧交通的code.md(46.6 KB)與 邊坡種子.md(41.4 KB),兩篇合計就占了全部位元組的 47%;最小的一篇是 汽車音響.md,只有 92 位元組。Totals: 42 notes, 191,093 bytes in all (about 186.6 KB). 19 notes carry HackMD tags and 23 have none. The two largest notes are 智慧交通的code.md (46.6 KB) and 邊坡種子.md (41.4 KB); together they hold 47 percent of every byte in the export. The smallest note is 汽車音響.md at just 92 bytes.合計:42 ノート、総計 191,093 バイト(約 186.6 KB)。HackMD のタグ付きは 19 本、タグなしは 23 本。最大の二本は 智慧交通的code.md(46.6 KB)と 邊坡種子.md(41.4 KB)で、この二本だけでエクスポート全体の 47% を占める。最小は 汽車音響.md で、わずか 92 バイトである。

回到頂端 ↑Back to top ↑ページ上部へ ↑