SDHostController.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. /*
  2. * Copyright (c) 2023, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Format.h>
  7. #include <AK/StdLibExtras.h>
  8. #include <Kernel/Devices/DeviceManagement.h>
  9. #include <Kernel/Devices/Storage/SD/Commands.h>
  10. #include <Kernel/Devices/Storage/SD/SDHostController.h>
  11. #include <Kernel/Devices/Storage/StorageManagement.h>
  12. #include <Kernel/Time/TimeManagement.h>
  13. #if ARCH(AARCH64)
  14. # include <Kernel/Arch/aarch64/RPi/SDHostController.h>
  15. #endif
  16. namespace Kernel {
  17. // Relevant Specifications:
  18. // * (SDHC): SD Host Controller Simplified Specification (https://www.sdcard.org/downloads/pls/)
  19. // * (PLSS) Physical Layer Simplified Specification (https://www.sdcard.org/downloads/pls/)
  20. // * (BCM2835) BCM2835 ARM Peripherals (https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf)
  21. static void delay(i64 nanoseconds)
  22. {
  23. auto start = TimeManagement::the().monotonic_time();
  24. auto end = start + Duration::from_nanoseconds(nanoseconds);
  25. while (TimeManagement::the().monotonic_time() < end)
  26. Processor::pause();
  27. }
  28. constexpr u32 max_supported_sdsc_frequency = 25000000;
  29. constexpr u32 max_supported_sdsc_frequency_high_speed = 50000000;
  30. // In "m_registers->host_configuration_0"
  31. // 2.2.11 Host Control 1 Register
  32. constexpr u32 high_speed_enable = 1 << 2;
  33. constexpr u32 dma_select_adma2_32 = 0b10 << 3;
  34. constexpr u32 dma_select_adma2_64 = 0b11 << 3;
  35. // In "m_registers->host_configuration_1"
  36. // In sub-register "Clock Control"
  37. constexpr u32 internal_clock_enable = 1 << 0;
  38. constexpr u32 internal_clock_stable = 1 << 1;
  39. constexpr u32 sd_clock_enable = 1 << 2;
  40. // In sub-register "Software Reset"
  41. constexpr u32 software_reset_for_all = 0x01000000;
  42. // In Interrupt Status Register
  43. constexpr u32 command_complete = 1 << 0;
  44. constexpr u32 transfer_complete = 1 << 1;
  45. constexpr u32 buffer_write_ready = 1 << 4;
  46. constexpr u32 buffer_read_ready = 1 << 5;
  47. // PLSS 5.1: all voltage windows
  48. constexpr u32 acmd41_voltage = 0x00ff8000;
  49. // PLSS 4.2.3.1: All voltage windows, XPC = 1, SDHC = 1
  50. constexpr u32 acmd41_arg = 0x50ff8000;
  51. constexpr size_t block_len = 512;
  52. SDHostController::SDHostController()
  53. : StorageController(StorageManagement::generate_relative_sd_controller_id({}))
  54. {
  55. }
  56. ErrorOr<void> SDHostController::reset() { return ENOTIMPL; }
  57. ErrorOr<void> SDHostController::shutdown() { return ENOTIMPL; }
  58. void SDHostController::complete_current_request(AsyncDeviceRequest::RequestResult)
  59. {
  60. VERIFY_NOT_REACHED();
  61. }
  62. ErrorOr<void> SDHostController::initialize()
  63. {
  64. m_registers = get_register_map_base_address();
  65. if (!m_registers)
  66. return EIO;
  67. if (host_version() != SD::HostVersion::Version3 && host_version() != SD::HostVersion::Version2)
  68. return ENOTSUP;
  69. TRY(reset_host_controller());
  70. m_registers->interrupt_status_enable = 0xffffffff;
  71. auto card_or_error = try_initialize_inserted_card();
  72. if (card_or_error.is_error() && card_or_error.error().code() != ENODEV) {
  73. dmesgln("SDHostController: Failed to initialize inserted card: {}", card_or_error.error());
  74. } else if (!card_or_error.is_error()) {
  75. m_card = card_or_error.release_value();
  76. }
  77. return {};
  78. }
  79. void SDHostController::try_enable_dma()
  80. {
  81. if (m_registers->capabilities.adma2) {
  82. auto maybe_dma_buffer = MM.allocate_dma_buffer_pages(dma_region_size, "SDHC DMA Buffer"sv, Memory::Region::Access::ReadWrite);
  83. if (maybe_dma_buffer.is_error()) {
  84. dmesgln("Could not allocate DMA pages for SDHC: {}", maybe_dma_buffer.error());
  85. } else {
  86. m_dma_region = maybe_dma_buffer.release_value();
  87. dbgln("Allocated SDHC DMA buffer at {}", m_dma_region->physical_page(0)->paddr());
  88. // FIXME: This check does not seem to work, qemu supports 64 bit addressing, but we don't seem to detect it
  89. // FIXME: Hardcoding to use the 64 bit mode leads to transfer timeouts, without any errors reported from qemu
  90. if (host_version() != SD::HostVersion::Version3 && m_registers->capabilities.dma_64_bit_addressing_v3) {
  91. dbgln("Setting SDHostController to operate using ADMA2 with 64 bit addressing");
  92. m_mode = OperatingMode::ADMA2_64;
  93. m_registers->host_configuration_0 = m_registers->host_configuration_0 | dma_select_adma2_64;
  94. } else {
  95. // FIXME: Use a way that guarantees memory addresses below the 32 bit threshold
  96. VERIFY(m_dma_region->physical_page(0)->paddr().get() >> 32 == 0);
  97. VERIFY(m_dma_region->physical_page(dma_region_size / PAGE_SIZE - 1)->paddr().get() >> 32 == 0);
  98. dbgln("Setting SDHostController to operate using ADMA2 with 32 bit addressing");
  99. m_mode = OperatingMode::ADMA2_32;
  100. m_registers->host_configuration_0 = m_registers->host_configuration_0 | dma_select_adma2_32;
  101. }
  102. }
  103. }
  104. }
  105. ErrorOr<NonnullLockRefPtr<SDMemoryCard>> SDHostController::try_initialize_inserted_card()
  106. {
  107. if (!is_card_inserted())
  108. return ENODEV;
  109. // PLSS 4.2: "Card Identification Mode"
  110. // "After power-on ...the cards are initialized with ... 400KHz clock frequency."
  111. // NOTE: The SDHC might already have been initialized (e.g. by the bootloader), let's reset it to a known configuration
  112. if (is_sd_clock_enabled())
  113. sd_clock_stop();
  114. TRY(sd_clock_supply(400000));
  115. // PLSS 4.2.3: "Card Initialization and Identification Process"
  116. // Also see Figure 4-2 in the PLSS spec for a flowchart of the initialization process.
  117. // Note that the steps correspond to the steps in the flowchart, although I made up the numbering and text
  118. // 1. Send CMD0 (GO_IDLE_STATE) to the card
  119. TRY(issue_command(SD::Commands::go_idle_state, 0));
  120. TRY(wait_for_response());
  121. // 2. Send CMD8 (SEND_IF_COND) to the card
  122. // SD interface condition: 7:0 = check pattern, 11:8 = supply voltage
  123. // 0x1aa: check pattern = 10101010, supply voltage = 1 => 2.7-3.6V
  124. const u32 voltage_window = 0x1aa;
  125. TRY(issue_command(SD::Commands::send_if_cond, voltage_window));
  126. auto interface_condition_response = wait_for_response();
  127. // 3. If the card does not respond to CMD8 it means that (Ver2.00 or later
  128. // SD Memory Card(voltage mismatch) or Ver1.X SD Memory Card or not SD
  129. // Memory Card)
  130. if (interface_condition_response.is_error()) {
  131. // TODO: This is supposed to be the "No Response" branch of the
  132. // flowchart in Figure 4-2 of the PLSS spec
  133. return ENOTSUP;
  134. }
  135. // 4. If the card responds to CMD8, but it's not a valid response then the
  136. // card is not usable
  137. if (interface_condition_response.value().response[0] != voltage_window) {
  138. // FIXME: We should probably try again with a lower voltage window
  139. return ENODEV;
  140. }
  141. // 5. Send ACMD41 (SEND_OP_COND) with HCS=1 to the card, repeat this until the card is ready or timeout
  142. SD::OperatingConditionRegister ocr = {};
  143. bool card_is_usable = true;
  144. if (!retry_with_timeout([&]() {
  145. if (issue_command(SD::Commands::app_cmd, 0).is_error() || wait_for_response().is_error())
  146. return false;
  147. if (issue_command(SD::Commands::app_send_op_cond, acmd41_arg).is_error())
  148. return false;
  149. if (auto acmd41_response = wait_for_response();
  150. !acmd41_response.is_error()) {
  151. // 20. Check if the card supports the voltage windows we requested and SDHC
  152. u32 response = acmd41_response.value().response[0];
  153. if ((response & acmd41_voltage) != acmd41_voltage) {
  154. card_is_usable = false;
  155. return false;
  156. }
  157. ocr.raw = acmd41_response.value().response[0];
  158. }
  159. return ocr.card_power_up_status == 1;
  160. })) {
  161. return card_is_usable ? EIO : ENODEV;
  162. }
  163. // 6. If you requested to switch to 1.8V, and the card accepts, execute a voltage switch sequence
  164. // (we didn't ask it)
  165. // 7. Send CMD2 (ALL_SEND_CID) to the card
  166. TRY(issue_command(SD::Commands::all_send_cid, 0));
  167. auto all_send_cid_response = TRY(wait_for_response());
  168. auto cid = bit_cast<SD::CardIdentificationRegister>(all_send_cid_response.response);
  169. // 8. Send CMD3 (SEND_RELATIVE_ADDR) to the card
  170. TRY(issue_command(SD::Commands::send_relative_addr, 0));
  171. auto send_relative_addr_response = TRY(wait_for_response());
  172. u32 rca = send_relative_addr_response.response[0]; // FIXME: Might need to clear some bits here
  173. // Extra steps:
  174. TRY(issue_command(SD::Commands::send_csd, rca));
  175. auto send_csd_response = TRY(wait_for_response());
  176. auto csd = bit_cast<SD::CardSpecificDataRegister>(send_csd_response.response);
  177. u32 block_count = (csd.device_size + 1) * (1 << (csd.device_size_multiplier + 2));
  178. u32 block_size = (1 << csd.max_read_data_block_length);
  179. u64 capacity = static_cast<u64>(block_count) * block_size;
  180. u64 card_capacity_in_blocks = capacity / block_len;
  181. if (m_registers->capabilities.high_speed) {
  182. dbgln("SDHC: Enabling High Speed mode");
  183. m_registers->host_configuration_0 = m_registers->host_configuration_0 | high_speed_enable;
  184. TRY(sd_clock_frequency_change(max_supported_sdsc_frequency_high_speed));
  185. } else {
  186. TRY(sd_clock_frequency_change(max_supported_sdsc_frequency));
  187. }
  188. TRY(issue_command(SD::Commands::select_card, rca));
  189. TRY(wait_for_response());
  190. // Set block length to 512 if the card is SDSC.
  191. // All other models only support 512 byte blocks so they don't need to be explicitly told
  192. if (!ocr.card_capacity_status) {
  193. TRY(issue_command(SD::Commands::set_block_len, block_len));
  194. TRY(wait_for_response());
  195. }
  196. auto scr = TRY(retrieve_sd_configuration_register(rca));
  197. TRY(issue_command(SD::Commands::app_cmd, rca));
  198. TRY(wait_for_response());
  199. TRY(issue_command(SD::Commands::app_set_bus_width, 0x2)); // 0b00=1 bit bus, 0b10=4 bit bus
  200. TRY(wait_for_response());
  201. return TRY(DeviceManagement::try_create_device<SDMemoryCard>(
  202. *this,
  203. StorageDevice::LUNAddress { controller_id(), 0, 0 },
  204. hardware_relative_controller_id(), block_len,
  205. card_capacity_in_blocks, rca, ocr, cid, scr));
  206. }
  207. bool SDHostController::retry_with_timeout(Function<bool()> f, i64 delay_between_tries)
  208. {
  209. int timeout = 1000;
  210. bool success = false;
  211. while (!success && timeout > 0) {
  212. success = f();
  213. if (!success)
  214. delay(delay_between_tries);
  215. timeout--;
  216. }
  217. return timeout > 0;
  218. }
  219. ErrorOr<void> SDHostController::issue_command(SD::Command const& cmd, u32 argument)
  220. {
  221. // SDHC 3.7.1: "Transaction Control without Data Transfer Using DAT Line"
  222. // 1. Check Command Inhibit (CMD) in the Present State register.
  223. // Repeat this step until Command Inhibit (CMD) is 0.
  224. // That is, when Command Inhibit (CMD) is 1, the Host Driver
  225. // shall not issue an SD Command.
  226. if (!retry_with_timeout([&]() { return !m_registers->present_state.command_inhibit_cmd; })) {
  227. return EIO;
  228. }
  229. // 2. If the Host Driver issues an SD Command using DAT lines
  230. // including busy signal, go to step (3).
  231. // If without using DAT lines including busy signal, go to step (5).
  232. // 3. If the Host Driver is issuing an abort command, go to step (5). In the
  233. // case of non-abort command, go to step (4).
  234. if (cmd.requires_dat_line() && cmd.type != SD::CommandType::Abort) {
  235. // 4. Check Command Inhibit (DAT) in the Present State register. Repeat
  236. // this step until Command Inhibit (DAT) is set to 0.
  237. if (!retry_with_timeout([&]() { return !m_registers->present_state.command_inhibit_dat; })) {
  238. return EIO;
  239. }
  240. }
  241. // 5. Set registers as described in Table 1-2 except Command register.
  242. m_registers->argument_1 = argument;
  243. // 6. Set the Command register.
  244. m_registers->transfer_mode_and_command = cmd.raw;
  245. // 7. Perform Command Completion Sequence in accordance with 3.7.1.2.
  246. // Done in wait_for_response()
  247. return {};
  248. }
  249. ErrorOr<SDHostController::Response> SDHostController::wait_for_response()
  250. {
  251. // SDHC 3.7.1.2 The Sequence to Finalize a Command
  252. // 1. Wait for the Command Complete Interrupt. If the Command Complete
  253. // Interrupt has occurred, go to step (2).
  254. if (!retry_with_timeout(
  255. [&]() { return m_registers->interrupt_status.command_complete; })) {
  256. return EIO;
  257. }
  258. // 2. Write 1 to Command Complete in the Normal Interrupt Status register to clear this bit
  259. m_registers->interrupt_status.raw = command_complete;
  260. // 3. Read the Response register(s) to get the response.
  261. // NOTE: We read fewer bits than ResponseType because the missing bits are only
  262. // relevant for the physical layer, and the device filters them before they
  263. // reach us
  264. Response r = {};
  265. auto cmd = last_sent_command();
  266. switch (cmd.response_type) {
  267. case SD::ResponseType::NoResponse:
  268. break;
  269. case SD::ResponseType::ResponseOf136Bits:
  270. r.response[0] = m_registers->response_0;
  271. r.response[1] = m_registers->response_1;
  272. r.response[2] = m_registers->response_2;
  273. r.response[3] = m_registers->response_3;
  274. break;
  275. case SD::ResponseType::ResponseOf48Bits:
  276. r.response[0] = m_registers->response_0;
  277. break;
  278. case SD::ResponseType::ResponseOf48BitsWithBusy:
  279. // FIXME: Idk what to do here
  280. break;
  281. }
  282. // 4. Judge whether the command uses the Transfer Complete Interrupt or not.
  283. // If it uses Transfer Complete, go to step (5). If not, go to step (7).
  284. if (last_sent_command().uses_transfer_complete_interrupt())
  285. TODO();
  286. // 7. Check for errors in Response Data. If there is no error, go to step (8). If there is an error, go to step (9).
  287. if (cmd.response_type != SD::ResponseType::ResponseOf136Bits) {
  288. if (card_status_contains_errors(cmd, r.response[0])) {
  289. return EIO;
  290. }
  291. }
  292. // NOTE: Steps 7, 8 and 9 consist of checking the response for errors, which
  293. // are specific to each command therefore those steps are not fully implemented
  294. // here.
  295. return { r };
  296. }
  297. bool SDHostController::is_sd_clock_enabled()
  298. {
  299. return m_registers->host_configuration_1 & sd_clock_enable;
  300. }
  301. ErrorOr<u32> SDHostController::calculate_sd_clock_divisor(u32 sd_clock_frequency, u32 frequency)
  302. {
  303. // SDHC 2.2.14: "Clock Control Register"
  304. // (1) 10-bit Divisor Mode
  305. // This mode is supported by the Host Controller Version 1.00 and 2.00.
  306. // The frequency is not programmed directly; rather this register holds the divisor of
  307. // the Base Clock Frequency For SD Clock in the Capabilities register. Only
  308. // the following settings are allowed.
  309. //
  310. // +-----+---------------------------+
  311. // | 80h | base clock divided by 256 |
  312. // | 40h | base clock divided by 128 |
  313. // | 20h | base clock divided by 64 |
  314. // | 10h | base clock divided by 32 |
  315. // | 08h | base clock divided by 16 |
  316. // | 04h | base clock divided by 8 |
  317. // | 02h | base clock divided by 4 |
  318. // | 01h | base clock divided by 2 |
  319. // | 00h | Base clock (10MHz-63MHz) |
  320. // +-----+---------------------------+
  321. //
  322. if (host_version() == SD::HostVersion::Version2 || host_version() == SD::HostVersion::Version1) {
  323. for (u32 divisor = 1; divisor <= 256; divisor *= 2) {
  324. if (sd_clock_frequency / divisor <= frequency)
  325. return divisor >> 1;
  326. }
  327. dmesgln("SDHostController: Could not find a suitable divisor for the requested frequency");
  328. return ENOTSUP;
  329. }
  330. // (2) 10-bit Divided Clock Mode
  331. // Host Controller Version 3.00 supports this mandatory mode instead of the
  332. // 8-bit Divided Clock Mode. The length of divider is extended to 10 bits and all
  333. // divider values shall be supported.
  334. //
  335. // +------+-------------------------------+
  336. // | 3FFh | 1/2046 Divided Clock |
  337. // | .... | ............................. |
  338. // | N | 1/2N Divided Clock (Duty 50%) |
  339. // | .... | ............................. |
  340. // | 002h | 1/4 Divided Clock |
  341. // | 001h | 1/2 Divided Clock |
  342. // | 000h | Base Clock (10MHz-255MHz) |
  343. // +------+-------------------------------+
  344. //
  345. if (host_version() == SD::HostVersion::Version3) {
  346. if (frequency == sd_clock_frequency)
  347. return 0;
  348. auto divisor = AK::ceil_div(sd_clock_frequency, 2 * frequency);
  349. if (divisor > 0x3ff) {
  350. dmesgln("SDHostController: Cannot represent the divisor for the requested frequency");
  351. return ENOTSUP;
  352. }
  353. return divisor;
  354. }
  355. VERIFY_NOT_REACHED();
  356. }
  357. ErrorOr<void> SDHostController::sd_clock_supply(u32 frequency)
  358. {
  359. // SDHC 3.2.1: "SD Clock Supply Sequence"
  360. // The *Clock Control* register is in the lower 16 bits of *Host Configuration 1*
  361. VERIFY((m_registers->host_configuration_1 & sd_clock_enable) == 0);
  362. // 1. Find out the divisor to determine the SD Clock Frequency
  363. const u32 sd_clock_frequency = TRY(retrieve_sd_clock_frequency());
  364. u32 divisor = TRY(calculate_sd_clock_divisor(sd_clock_frequency, frequency));
  365. // 2. Set Internal Clock Enable and SDCLK Frequency Select in the Clock Control register
  366. const u32 eight_lower_bits_of_sdclk_frequency_select = (divisor & 0xff) << 8;
  367. u32 sdclk_frequency_select = eight_lower_bits_of_sdclk_frequency_select;
  368. if (host_version() == SD::HostVersion::Version3) {
  369. const u32 two_upper_bits_of_sdclk_frequency_select = (divisor >> 8 & 0x3) << 6;
  370. sdclk_frequency_select |= two_upper_bits_of_sdclk_frequency_select;
  371. }
  372. m_registers->host_configuration_1 = m_registers->host_configuration_1 | internal_clock_enable | sdclk_frequency_select;
  373. // 3. Check Internal Clock Stable in the Clock Control register until it is 1
  374. if (!retry_with_timeout([&] { return m_registers->host_configuration_1 & internal_clock_stable; })) {
  375. return EIO;
  376. }
  377. // 4. Set SD Clock Enable in the Clock Control register to 1
  378. m_registers->host_configuration_1 = m_registers->host_configuration_1 | sd_clock_enable;
  379. return {};
  380. }
  381. void SDHostController::sd_clock_stop()
  382. {
  383. // SDHC 3.2.2: "SD Clock Stop Sequence"
  384. // 1. Set SD Clock Enable in the Clock Control register to 0
  385. m_registers->host_configuration_1 = m_registers->host_configuration_1 & ~sd_clock_enable;
  386. }
  387. ErrorOr<void> SDHostController::sd_clock_frequency_change(u32 new_frequency)
  388. {
  389. // SDHC 3.2.3: "SD Clock Frequency Change Sequence"
  390. // 1. Execute the SD Clock Stop Sequence
  391. sd_clock_stop();
  392. // 2. Execute the SD Clock Supply Sequence
  393. return sd_clock_supply(new_frequency);
  394. }
  395. ErrorOr<void> SDHostController::reset_host_controller()
  396. {
  397. m_registers->host_configuration_0 = 0;
  398. m_registers->host_configuration_1 = m_registers->host_configuration_1 | software_reset_for_all;
  399. if (!retry_with_timeout(
  400. [&] {
  401. return (m_registers->host_configuration_1 & software_reset_for_all) == 0;
  402. })) {
  403. return EIO;
  404. }
  405. return {};
  406. }
  407. ErrorOr<void> SDHostController::transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  408. SD::Command const& command,
  409. u32 argument,
  410. u32 block_count,
  411. u32 block_size,
  412. UserOrKernelBuffer buf,
  413. DataTransferType data_transfer_type)
  414. {
  415. // SDHC 3.7.2: "Transaction Control with Data Transfer Using DAT Line (without DMA)"
  416. // 1. Set the value corresponding to the executed data byte length of one block to Block Size register.
  417. // 2. Set the value corresponding to the executed data block count to Block Count register in accordance with Table 2-8.
  418. m_registers->block_size_and_block_count = (block_count << 16) | block_size;
  419. // 3. Set the argument value to Argument 1 register.
  420. m_registers->argument_1 = argument;
  421. // 4. Set the value to the Transfer Mode register. The host driver
  422. // determines Multi / Single Block
  423. // Select, Block Count Enable, Data Transfer Direction, Auto CMD12 Enable
  424. // and DMA Enable. Multi / Single Block Select and Block Count Enable are
  425. // determined according to Table 2-8. (NOTE: We assume `cmd` already has
  426. // the correct flags set)
  427. // 5. Set the value to Command register.
  428. m_registers->transfer_mode_and_command = command.raw;
  429. // 6. Then, wait for the Command Complete Interrupt.
  430. if (!retry_with_timeout([&]() { return m_registers->interrupt_status.command_complete; })) {
  431. return EIO;
  432. }
  433. // 7. Write 1 to the Command Complete in the Normal Interrupt Status
  434. // register for clearing this bit.
  435. m_registers->interrupt_status.raw = command_complete;
  436. // 8. Read Response register and get necessary information of the issued
  437. // command
  438. // (FIXME: Return the value for better error handling)
  439. // 9. In the case where this sequence is for write to a card, go to step
  440. // (10).
  441. // In case of read from a card, go to step (14).
  442. if (data_transfer_type == DataTransferType::Write) {
  443. for (u32 i = 0; i < block_count; i++) {
  444. // 10. Then wait for Buffer Write Ready Interrupt.
  445. if (!retry_with_timeout(
  446. [&]() {
  447. return m_registers->interrupt_status.buffer_write_ready;
  448. })) {
  449. return EIO;
  450. }
  451. // 11. Write 1 to the Buffer Write Ready in the Normal Interrupt Status register for clearing this bit.
  452. m_registers->interrupt_status.raw = buffer_write_ready;
  453. // 12. Write block data (in according to the number of bytes specified at the step (1)) to Buffer Data Port register.
  454. u32 temp;
  455. for (u32 j = 0; j < block_size / sizeof(u32); j++) {
  456. TRY(buf.read(&temp, i * block_size + sizeof(u32) * j, sizeof(u32)));
  457. m_registers->buffer_data_port = temp;
  458. }
  459. // 13. Repeat until all blocks are sent and then go to step (18).
  460. }
  461. } else {
  462. for (u32 i = 0; i < block_count; i++) {
  463. // 14. Then wait for the Buffer Read Ready Interrupt.
  464. if (!retry_with_timeout([&]() { return m_registers->interrupt_status.buffer_read_ready; })) {
  465. return EIO;
  466. }
  467. // 15. Write 1 to the Buffer Read Ready in the Normal Interrupt Status
  468. // register for clearing this bit.
  469. m_registers->interrupt_status.raw = buffer_read_ready;
  470. // 16. Read block data (in according to the number of bytes specified at
  471. // the step (1)) from the Buffer Data Port register
  472. u32 temp;
  473. for (u32 j = 0; j < block_size / sizeof(u32); j++) {
  474. temp = m_registers->buffer_data_port;
  475. TRY(buf.write(&temp, i * block_size + sizeof(u32) * j, sizeof(u32)));
  476. }
  477. // 17. Repeat until all blocks are received and then go to step (18).
  478. }
  479. }
  480. // 18. If this sequence is for Single or Multiple Block Transfer, go to step
  481. // (19). In case of Infinite Block Transfer, go to step (21)
  482. // 19. Wait for Transfer Complete Interrupt.
  483. if (!retry_with_timeout(
  484. [&]() { return m_registers->interrupt_status.transfer_complete; })) {
  485. return EIO;
  486. }
  487. // 20. Write 1 to the Transfer Complete in the Normal Interrupt Status
  488. // register for clearing this bit
  489. m_registers->interrupt_status.raw = transfer_complete;
  490. return {};
  491. }
  492. u32 SDHostController::make_adma_descriptor_table(u32 block_count)
  493. {
  494. // FIXME: We might be able to write to the destination buffer directly
  495. // Especially with 64 bit addressing enabled
  496. // This might cost us more descriptor entries but avoids the memcpy at the end
  497. // of each read cycle
  498. FlatPtr adma_descriptor_physical = m_dma_region->physical_page(0)->paddr().get();
  499. FlatPtr adma_dma_region_physical = adma_descriptor_physical + PAGE_SIZE;
  500. FlatPtr adma_descriptor_virtual = m_dma_region->vaddr().get();
  501. u32 offset = 0;
  502. u32 blocks_transferred = 0;
  503. u32 blocks_per_descriptor = (1 << 16) / block_len;
  504. using enum OperatingMode;
  505. switch (m_mode) {
  506. case ADMA2_32: {
  507. u32 i = 0;
  508. Array<SD::DMADescriptor64, 64>& command_buffer = *bit_cast<Array<SD::DMADescriptor64, 64>*>(adma_descriptor_virtual);
  509. for (; i < 64; ++i) {
  510. FlatPtr physical_transfer_address = adma_dma_region_physical + offset;
  511. VERIFY(physical_transfer_address >> 32 == 0);
  512. // If the remaining block count is less than the maximum addressable blocks
  513. // we need to set the actual length and break out of the loop
  514. if (block_count - blocks_transferred < blocks_per_descriptor) {
  515. u32 blocks_to_transfer = block_count - blocks_transferred;
  516. command_buffer[i] = SD::DMADescriptor64 {
  517. .valid = 1,
  518. .end = 1,
  519. .interrupt = 0,
  520. .action = SD::DMAAction::Tran,
  521. .length_upper = 0,
  522. .length_lower = static_cast<u32>(blocks_to_transfer * block_len),
  523. .address = static_cast<u32>(physical_transfer_address),
  524. };
  525. blocks_transferred += blocks_to_transfer;
  526. offset += static_cast<size_t>(blocks_to_transfer) * block_len;
  527. break;
  528. }
  529. command_buffer[i] = SD::DMADescriptor64 {
  530. .valid = 1,
  531. .end = 0,
  532. .interrupt = 0,
  533. .action = SD::DMAAction::Tran,
  534. .length_upper = 0,
  535. .length_lower = 0, // length of 0 means 1<<16 bytes
  536. .address = static_cast<u32>(physical_transfer_address),
  537. };
  538. blocks_transferred += blocks_per_descriptor;
  539. offset += (1 << 16);
  540. }
  541. command_buffer[min(i, 63)].end = 1;
  542. break;
  543. }
  544. case ADMA2_64: {
  545. u32 i = 0;
  546. Array<SD::DMADescriptor128, 32>& command_buffer = *bit_cast<Array<SD::DMADescriptor128, 32>*>(adma_descriptor_virtual);
  547. for (; i < 32; ++i) {
  548. FlatPtr physical_transfer_address = adma_dma_region_physical + offset;
  549. VERIFY(physical_transfer_address >> 32 == 0);
  550. // If the remaining block count is less than the maximum addressable blocks
  551. // we need to set the actual length and break out of the loop
  552. if (block_count - blocks_transferred < blocks_per_descriptor) {
  553. u32 blocks_to_read = block_count - blocks_transferred;
  554. command_buffer[i] = SD::DMADescriptor128 {
  555. .valid = 1,
  556. .end = 1,
  557. .interrupt = 0,
  558. .action = SD::DMAAction::Tran,
  559. .length_upper = 0,
  560. .length_lower = static_cast<u32>(blocks_to_read * block_len),
  561. .address_low = static_cast<u32>((physical_transfer_address + offset) & 0xFFFF'FFFF),
  562. .address_high = static_cast<u32>((physical_transfer_address + offset) >> 32),
  563. };
  564. blocks_transferred += blocks_to_read;
  565. offset += static_cast<size_t>(blocks_to_read) * block_len;
  566. break;
  567. }
  568. command_buffer[i] = SD::DMADescriptor128 {
  569. .valid = 1,
  570. .end = 0,
  571. .interrupt = 0,
  572. .action = SD::DMAAction::Tran,
  573. .length_upper = 0,
  574. .length_lower = 0, // length of 0 means 1<<16 bytes
  575. .address_low = static_cast<u32>((physical_transfer_address + offset) & 0xFFFF'FFFF),
  576. .address_high = static_cast<u32>((physical_transfer_address + offset) >> 32),
  577. };
  578. blocks_transferred += blocks_per_descriptor;
  579. offset += (1 << 16);
  580. }
  581. command_buffer[min(i, 31)].end = 1;
  582. break;
  583. }
  584. case PIO:
  585. VERIFY_NOT_REACHED();
  586. }
  587. return blocks_transferred;
  588. }
  589. ErrorOr<void> SDHostController::transfer_blocks_adma2(u32 block_address, u32 block_count, UserOrKernelBuffer out, SD::DataTransferDirection direction)
  590. {
  591. using enum OperatingMode;
  592. FlatPtr adma_descriptor_physical = m_dma_region->physical_page(0)->paddr().get();
  593. FlatPtr adma_descriptor_virtual = m_dma_region->vaddr().get();
  594. FlatPtr adma_dma_region_virtual = adma_descriptor_virtual + PAGE_SIZE;
  595. AK::ArmedScopeGuard abort_guard {
  596. [] {
  597. dbgln("Aborting SDHC ADMA read");
  598. TODO();
  599. }
  600. };
  601. // 3.7.2.3 Using ADMA
  602. u32 blocks_per_descriptor = (1 << 16) / block_len;
  603. u32 addressable_blocks_per_transfer = blocks_per_descriptor * (m_mode == ADMA2_32 ? 64 : 32);
  604. size_t host_offset = 0;
  605. size_t card_offset = 0;
  606. u32 blocks_transferred_total = 0;
  607. while (blocks_transferred_total < block_count) {
  608. // When writing to the card we must prime the transfer buffer with the data we want to write
  609. // FIXME: We might be able to transfer to/from the destination/origin buffer directly
  610. // Especially with 64 bit addressing enabled
  611. // This might cost us more descriptor entries, when the physical range is segmented,
  612. // but avoids the memcpy at the end of each transfer cycle
  613. if (direction == SD::DataTransferDirection::HostToCard)
  614. TRY(out.read(bit_cast<void*>(adma_dma_region_virtual), host_offset, min(block_count - blocks_transferred_total, addressable_blocks_per_transfer) * block_len));
  615. // (1) Create Descriptor table for ADMA in the system memory
  616. u32 blocks_transferred = make_adma_descriptor_table(block_count);
  617. card_offset += blocks_transferred * block_len;
  618. // (2) Set the Descriptor address for ADMA in the ADMA System Address register.
  619. m_registers->adma_system_address[0] = static_cast<u32>(adma_descriptor_physical & 0xFFFF'FFFF);
  620. if (m_mode == ADMA2_64)
  621. m_registers->adma_system_address[1] = static_cast<u32>(adma_descriptor_physical >> 32);
  622. // (3) Set the value corresponding to the executed data byte length of one block in the Block Size
  623. // register.
  624. // (4) Set the value corresponding to the executed data block count in the Block Count register in
  625. // accordance with Table 2-9. Refer to Section 1.15 for more details.
  626. // Note: To avoid the restriction of the 16 bit block count we disable the block counter
  627. // and do not set the block count, resulting in an "Infinite Transfer" (SDHC Table 2-9)
  628. // ADMA has its own way of encoding block counts and to signal transfer termination
  629. m_registers->block_size_and_block_count = block_len;
  630. // (5) Set the argument value to the Argument register.
  631. m_registers->argument_1 = block_address;
  632. // (6) Set the value to the Transfer Mode register. The Host Driver determines Multi / Single Block
  633. // Select, Block Count Enable, Data Transfer Direction, Auto CMD12 Enable and DMA
  634. // Enable. Multi / Single Block Select and Block Count Enable are determined according to
  635. // Table 2-9.
  636. // If response check is enabled (Response Error Check Enable =1), set Response Interrupt
  637. // Disable to 1 and select Response Type R1 / R5
  638. SD::Command command = {
  639. .dma_enable = 1,
  640. .block_counter = 0,
  641. .auto_command = blocks_transferred > 1 ? SD::SendAutoCommand::Command12 : SD::SendAutoCommand::Disabled,
  642. .direction = direction,
  643. .multiblock = blocks_transferred > 1,
  644. .response_type_r1r5 = 0,
  645. .response_error_check = 0,
  646. .response_interrupt_disable = 0,
  647. .reserved1 = 0,
  648. .response_type = SD::ResponseType::ResponseOf48Bits,
  649. .sub_command_flag = 0,
  650. .crc_enable = 1,
  651. .idx_enable = 0,
  652. .is_data = 1,
  653. .type = SD::CommandType::Normal,
  654. .index = direction == SD::DataTransferDirection::HostToCard ? (blocks_transferred > 1 ? SD::CommandIndex::WriteMultipleBlock : SD::CommandIndex::WriteSingleBlock)
  655. : (blocks_transferred > 1 ? SD::CommandIndex::ReadMultipleBlock : SD::CommandIndex::ReadSingleBlock),
  656. .reserved3 = 0
  657. };
  658. // (7) Set the value to the Command register.
  659. // Note: When writing to the upper byte [3] of the Command register, the SD command is issued
  660. // and DMA is started.
  661. m_registers->transfer_mode_and_command = command.raw;
  662. // (8) If response check is enabled, go to stop (11) else wait for the Command Complete Interrupt.
  663. // Note: We never enabled response checking
  664. if (!retry_with_timeout([this]() { return m_registers->interrupt_status.command_complete; })) {
  665. dbgln("SDHC: ADMA2 command response timed out");
  666. }
  667. // (9) Write 1 to the Command Complete in the Normal Interrupt Status register to clear this bit.
  668. // Note: We cannot write to the nit field member directly, due to that also possibly
  669. // setting the already completed `transfer_complete` flag, making the next check time out.
  670. m_registers->interrupt_status.raw = command_complete;
  671. // TODO: (10) Read Response register and get necessary information of the issued command
  672. // (11) Wait for the Transfer Complete Interrupt and ADMA Error Interrupt.
  673. // FIXME: Especially with big transfers this might timeout before the transfer is finished, although
  674. // No error has has happened
  675. // We should set this up so that it actually waits for the interrupts via a designated handler
  676. // Note, that the SDHC has a way to detect transfer timeouts on its own
  677. if (!retry_with_timeout([this]() { return m_registers->interrupt_status.transfer_complete || m_registers->interrupt_status.adma_error; })) {
  678. dbgln("SDHC: ADMA2 transfer timed out");
  679. return EIO;
  680. }
  681. // (12) If Transfer Complete is set to 1, go to Step (13)
  682. if (m_registers->interrupt_status.transfer_complete) {
  683. // (13) Write 1 to the Transfer Complete Status in the Normal Interrupt Status register to clear this bit.
  684. m_registers->interrupt_status.transfer_complete = 1;
  685. }
  686. // else if ADMA Error Interrupt is set to 1, go to Step (14).
  687. else if (m_registers->interrupt_status.adma_error) {
  688. // (14) Write 1 to the ADMA Error Interrupt Status in the Error Interrupt Status register to clear this bit.
  689. m_registers->interrupt_status.adma_error = 1;
  690. // (15) Abort ADMA operation. SD card operation should be stopped by issuing abort command. If
  691. // necessary, the Host Driver checks ADMA Error Status register to detect why ADMA error is
  692. // generated
  693. dmesgln("SDHC transfer failed, ADMA Error Status: {:2b}", AK::to_underlying(m_registers->adma_error_status.state));
  694. // The scope guard will handle the Abort
  695. return EIO;
  696. } else {
  697. VERIFY_NOT_REACHED();
  698. }
  699. // Copy the read data to the correct memory location
  700. // FIXME: As described above, we may be able to target the destination buffer directly
  701. if (direction == SD::DataTransferDirection::CardToHost)
  702. TRY(out.write(bit_cast<void const*>(adma_dma_region_virtual), host_offset, blocks_transferred * block_len));
  703. blocks_transferred_total += blocks_transferred;
  704. host_offset = card_offset;
  705. block_address += card_offset;
  706. card_offset = 0;
  707. }
  708. abort_guard.disarm();
  709. return {};
  710. }
  711. ErrorOr<void> SDHostController::read_block(Badge<SDMemoryCard>, u32 block_address, u32 block_count, UserOrKernelBuffer out)
  712. {
  713. VERIFY(is_card_inserted());
  714. using enum OperatingMode;
  715. switch (m_mode) {
  716. case OperatingMode::ADMA2_32:
  717. case OperatingMode::ADMA2_64:
  718. return transfer_blocks_adma2(block_address, block_count, out, SD::DataTransferDirection::CardToHost);
  719. case PIO: {
  720. if (block_count > 1) {
  721. return transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  722. SD::Commands::read_multiple_block,
  723. block_address,
  724. block_count,
  725. block_len,
  726. out,
  727. DataTransferType::Read);
  728. }
  729. return transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  730. SD::Commands::read_single_block,
  731. block_address,
  732. block_count,
  733. block_len,
  734. out,
  735. DataTransferType::Read);
  736. }
  737. default:
  738. VERIFY_NOT_REACHED();
  739. }
  740. }
  741. ErrorOr<void> SDHostController::write_block(Badge<SDMemoryCard>, u32 block_address, u32 block_count, UserOrKernelBuffer in)
  742. {
  743. VERIFY(is_card_inserted());
  744. using enum OperatingMode;
  745. switch (m_mode) {
  746. case OperatingMode::ADMA2_32:
  747. case OperatingMode::ADMA2_64:
  748. return transfer_blocks_adma2(block_address, block_count, in, SD::DataTransferDirection::HostToCard);
  749. case PIO: {
  750. if (block_count > 1) {
  751. return transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  752. SD::Commands::write_multiple_block,
  753. block_address,
  754. block_count,
  755. block_len,
  756. in,
  757. DataTransferType::Write);
  758. }
  759. return transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  760. SD::Commands::write_single_block,
  761. block_address,
  762. block_count,
  763. block_len,
  764. in,
  765. DataTransferType::Write);
  766. }
  767. default:
  768. VERIFY_NOT_REACHED();
  769. };
  770. }
  771. ErrorOr<SD::SDConfigurationRegister> SDHostController::retrieve_sd_configuration_register(u32 relative_card_address)
  772. {
  773. SD::SDConfigurationRegister scr;
  774. TRY(issue_command(SD::Commands::app_cmd, relative_card_address));
  775. TRY(wait_for_response());
  776. TRY(transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  777. SD::Commands::app_send_scr,
  778. 0, 1, 8,
  779. UserOrKernelBuffer::for_kernel_buffer(scr.raw), DataTransferType::Read));
  780. return scr;
  781. }
  782. ErrorOr<u32> SDHostController::retrieve_sd_clock_frequency()
  783. {
  784. if (m_registers->capabilities.base_clock_frequency == 0) {
  785. // Spec says:
  786. // If these bits are all 0, the Host System has to get information via another method
  787. TODO();
  788. }
  789. const i64 one_mhz = 1'000'000;
  790. return { m_registers->capabilities.base_clock_frequency * one_mhz };
  791. }
  792. // PLSS Table 4-43 : Card Status Field/Command
  793. bool SDHostController::card_status_contains_errors(SD::Command const& command, u32 resp)
  794. {
  795. SD::CardStatus status;
  796. // PLSS 4.9.5 R6
  797. if (command.index == SD::CommandIndex::SendRelativeAddr) {
  798. status.raw = (resp & 0x1fff) | ((resp & 0x2000) << 6) | ((resp & 0x4000) << 8) | ((resp & 0x8000) << 8);
  799. } else {
  800. status.raw = resp;
  801. }
  802. bool common_errors = status.error || status.cc_error || status.card_ecc_failed || status.illegal_command || status.com_crc_error || status.lock_unlock_failed || status.card_is_locked || status.wp_violation || status.erase_param || status.csd_overwrite;
  803. bool contains_errors = false;
  804. switch (command.index) {
  805. case SD::CommandIndex::SendRelativeAddr:
  806. if (status.error || status.illegal_command || status.com_crc_error) {
  807. contains_errors = true;
  808. }
  809. break;
  810. case SD::CommandIndex::SelectCard:
  811. if (common_errors) {
  812. contains_errors = true;
  813. }
  814. break;
  815. case SD::CommandIndex::SetBlockLen:
  816. if (common_errors || status.block_len_error) {
  817. contains_errors = true;
  818. }
  819. break;
  820. case SD::CommandIndex::ReadSingleBlock:
  821. case SD::CommandIndex::ReadMultipleBlock:
  822. if (common_errors || status.address_error || status.out_of_range) {
  823. contains_errors = true;
  824. }
  825. break;
  826. case SD::CommandIndex::WriteSingleBlock:
  827. case SD::CommandIndex::WriteMultipleBlock:
  828. if (common_errors || status.block_len_error || status.address_error || status.out_of_range) {
  829. contains_errors = true;
  830. }
  831. break;
  832. case SD::CommandIndex::AppSendScr:
  833. if (common_errors) {
  834. contains_errors = true;
  835. }
  836. break;
  837. case SD::CommandIndex::AppCmd:
  838. if (common_errors) {
  839. contains_errors = true;
  840. }
  841. break;
  842. default:
  843. break;
  844. }
  845. return contains_errors;
  846. }
  847. }