SDHostController.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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. constexpr u32 command_inhibit = 1 << 1;
  223. // 1. Check Command Inhibit (CMD) in the Present State register.
  224. // Repeat this step until Command Inhibit (CMD) is 0.
  225. // That is, when Command Inhibit (CMD) is 1, the Host Driver
  226. // shall not issue an SD Command.
  227. if (!retry_with_timeout(
  228. [&]() { return !(m_registers->present_state & command_inhibit); })) {
  229. return EIO;
  230. }
  231. // 2. If the Host Driver issues an SD Command using DAT lines
  232. // including busy signal, go to step (3).
  233. // If without using DAT lines including busy signal, go to step (5).
  234. // 3. If the Host Driver is issuing an abort command, go to step (5). In the
  235. // case of non-abort command, go to step (4).
  236. if (cmd.requires_dat_line() && cmd.type != SD::CommandType::Abort) {
  237. // 4. Check Command Inhibit (DAT) in the Present State register. Repeat
  238. // this step until Command Inhibit (DAT) is set to 0.
  239. constexpr u32 data_inhibit = 1 << 2;
  240. if (!retry_with_timeout([&]() { return !(m_registers->present_state & data_inhibit); })) {
  241. return EIO;
  242. }
  243. }
  244. // 5. Set registers as described in Table 1-2 except Command register.
  245. m_registers->argument_1 = argument;
  246. // 6. Set the Command register.
  247. m_registers->transfer_mode_and_command = cmd.raw;
  248. // 7. Perform Command Completion Sequence in accordance with 3.7.1.2.
  249. // Done in wait_for_response()
  250. return {};
  251. }
  252. ErrorOr<SDHostController::Response> SDHostController::wait_for_response()
  253. {
  254. // SDHC 3.7.1.2 The Sequence to Finalize a Command
  255. // 1. Wait for the Command Complete Interrupt. If the Command Complete
  256. // Interrupt has occurred, go to step (2).
  257. if (!retry_with_timeout(
  258. [&]() { return m_registers->interrupt_status.command_complete; })) {
  259. return EIO;
  260. }
  261. // 2. Write 1 to Command Complete in the Normal Interrupt Status register to clear this bit
  262. m_registers->interrupt_status.raw = command_complete;
  263. // 3. Read the Response register(s) to get the response.
  264. // NOTE: We read fewer bits than ResponseType because the missing bits are only
  265. // relevant for the physical layer, and the device filters them before they
  266. // reach us
  267. Response r = {};
  268. auto cmd = last_sent_command();
  269. switch (cmd.response_type) {
  270. case SD::ResponseType::NoResponse:
  271. break;
  272. case SD::ResponseType::ResponseOf136Bits:
  273. r.response[0] = m_registers->response_0;
  274. r.response[1] = m_registers->response_1;
  275. r.response[2] = m_registers->response_2;
  276. r.response[3] = m_registers->response_3;
  277. break;
  278. case SD::ResponseType::ResponseOf48Bits:
  279. r.response[0] = m_registers->response_0;
  280. break;
  281. case SD::ResponseType::ResponseOf48BitsWithBusy:
  282. // FIXME: Idk what to do here
  283. break;
  284. }
  285. // 4. Judge whether the command uses the Transfer Complete Interrupt or not.
  286. // If it uses Transfer Complete, go to step (5). If not, go to step (7).
  287. if (last_sent_command().uses_transfer_complete_interrupt())
  288. TODO();
  289. // 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).
  290. if (cmd.response_type != SD::ResponseType::ResponseOf136Bits) {
  291. if (card_status_contains_errors(cmd, r.response[0])) {
  292. return EIO;
  293. }
  294. }
  295. // NOTE: Steps 7, 8 and 9 consist of checking the response for errors, which
  296. // are specific to each command therefore those steps are not fully implemented
  297. // here.
  298. return { r };
  299. }
  300. bool SDHostController::is_sd_clock_enabled()
  301. {
  302. return m_registers->host_configuration_1 & sd_clock_enable;
  303. }
  304. ErrorOr<u32> SDHostController::calculate_sd_clock_divisor(u32 sd_clock_frequency, u32 frequency)
  305. {
  306. // SDHC 2.2.14: "Clock Control Register"
  307. // (1) 10-bit Divisor Mode
  308. // This mode is supported by the Host Controller Version 1.00 and 2.00.
  309. // The frequency is not programmed directly; rather this register holds the divisor of
  310. // the Base Clock Frequency For SD Clock in the Capabilities register. Only
  311. // the following settings are allowed.
  312. //
  313. // +-----+---------------------------+
  314. // | 80h | base clock divided by 256 |
  315. // | 40h | base clock divided by 128 |
  316. // | 20h | base clock divided by 64 |
  317. // | 10h | base clock divided by 32 |
  318. // | 08h | base clock divided by 16 |
  319. // | 04h | base clock divided by 8 |
  320. // | 02h | base clock divided by 4 |
  321. // | 01h | base clock divided by 2 |
  322. // | 00h | Base clock (10MHz-63MHz) |
  323. // +-----+---------------------------+
  324. //
  325. if (host_version() == SD::HostVersion::Version2 || host_version() == SD::HostVersion::Version1) {
  326. for (u32 divisor = 1; divisor <= 256; divisor *= 2) {
  327. if (sd_clock_frequency / divisor <= frequency)
  328. return divisor >> 1;
  329. }
  330. dmesgln("SDHostController: Could not find a suitable divisor for the requested frequency");
  331. return ENOTSUP;
  332. }
  333. // (2) 10-bit Divided Clock Mode
  334. // Host Controller Version 3.00 supports this mandatory mode instead of the
  335. // 8-bit Divided Clock Mode. The length of divider is extended to 10 bits and all
  336. // divider values shall be supported.
  337. //
  338. // +------+-------------------------------+
  339. // | 3FFh | 1/2046 Divided Clock |
  340. // | .... | ............................. |
  341. // | N | 1/2N Divided Clock (Duty 50%) |
  342. // | .... | ............................. |
  343. // | 002h | 1/4 Divided Clock |
  344. // | 001h | 1/2 Divided Clock |
  345. // | 000h | Base Clock (10MHz-255MHz) |
  346. // +------+-------------------------------+
  347. //
  348. if (host_version() == SD::HostVersion::Version3) {
  349. if (frequency == sd_clock_frequency)
  350. return 0;
  351. auto divisor = AK::ceil_div(sd_clock_frequency, 2 * frequency);
  352. if (divisor > 0x3ff) {
  353. dmesgln("SDHostController: Cannot represent the divisor for the requested frequency");
  354. return ENOTSUP;
  355. }
  356. return divisor;
  357. }
  358. VERIFY_NOT_REACHED();
  359. }
  360. ErrorOr<void> SDHostController::sd_clock_supply(u32 frequency)
  361. {
  362. // SDHC 3.2.1: "SD Clock Supply Sequence"
  363. // The *Clock Control* register is in the lower 16 bits of *Host Configuration 1*
  364. VERIFY((m_registers->host_configuration_1 & sd_clock_enable) == 0);
  365. // 1. Find out the divisor to determine the SD Clock Frequency
  366. const u32 sd_clock_frequency = TRY(retrieve_sd_clock_frequency());
  367. u32 divisor = TRY(calculate_sd_clock_divisor(sd_clock_frequency, frequency));
  368. // 2. Set Internal Clock Enable and SDCLK Frequency Select in the Clock Control register
  369. const u32 eight_lower_bits_of_sdclk_frequency_select = (divisor & 0xff) << 8;
  370. u32 sdclk_frequency_select = eight_lower_bits_of_sdclk_frequency_select;
  371. if (host_version() == SD::HostVersion::Version3) {
  372. const u32 two_upper_bits_of_sdclk_frequency_select = (divisor >> 8 & 0x3) << 6;
  373. sdclk_frequency_select |= two_upper_bits_of_sdclk_frequency_select;
  374. }
  375. m_registers->host_configuration_1 = m_registers->host_configuration_1 | internal_clock_enable | sdclk_frequency_select;
  376. // 3. Check Internal Clock Stable in the Clock Control register until it is 1
  377. if (!retry_with_timeout([&] { return m_registers->host_configuration_1 & internal_clock_stable; })) {
  378. return EIO;
  379. }
  380. // 4. Set SD Clock Enable in the Clock Control register to 1
  381. m_registers->host_configuration_1 = m_registers->host_configuration_1 | sd_clock_enable;
  382. return {};
  383. }
  384. void SDHostController::sd_clock_stop()
  385. {
  386. // SDHC 3.2.2: "SD Clock Stop Sequence"
  387. // 1. Set SD Clock Enable in the Clock Control register to 0
  388. m_registers->host_configuration_1 = m_registers->host_configuration_1 & ~sd_clock_enable;
  389. }
  390. ErrorOr<void> SDHostController::sd_clock_frequency_change(u32 new_frequency)
  391. {
  392. // SDHC 3.2.3: "SD Clock Frequency Change Sequence"
  393. // 1. Execute the SD Clock Stop Sequence
  394. sd_clock_stop();
  395. // 2. Execute the SD Clock Supply Sequence
  396. return sd_clock_supply(new_frequency);
  397. }
  398. ErrorOr<void> SDHostController::reset_host_controller()
  399. {
  400. m_registers->host_configuration_0 = 0;
  401. m_registers->host_configuration_1 = m_registers->host_configuration_1 | software_reset_for_all;
  402. if (!retry_with_timeout(
  403. [&] {
  404. return (m_registers->host_configuration_1 & software_reset_for_all) == 0;
  405. })) {
  406. return EIO;
  407. }
  408. return {};
  409. }
  410. ErrorOr<void> SDHostController::transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  411. SD::Command const& command,
  412. u32 argument,
  413. u32 block_count,
  414. u32 block_size,
  415. UserOrKernelBuffer buf,
  416. DataTransferType data_transfer_type)
  417. {
  418. // SDHC 3.7.2: "Transaction Control with Data Transfer Using DAT Line (without DMA)"
  419. // 1. Set the value corresponding to the executed data byte length of one block to Block Size register.
  420. // 2. Set the value corresponding to the executed data block count to Block Count register in accordance with Table 2-8.
  421. m_registers->block_size_and_block_count = (block_count << 16) | block_size;
  422. // 3. Set the argument value to Argument 1 register.
  423. m_registers->argument_1 = argument;
  424. // 4. Set the value to the Transfer Mode register. The host driver
  425. // determines Multi / Single Block
  426. // Select, Block Count Enable, Data Transfer Direction, Auto CMD12 Enable
  427. // and DMA Enable. Multi / Single Block Select and Block Count Enable are
  428. // determined according to Table 2-8. (NOTE: We assume `cmd` already has
  429. // the correct flags set)
  430. // 5. Set the value to Command register.
  431. m_registers->transfer_mode_and_command = command.raw;
  432. // 6. Then, wait for the Command Complete Interrupt.
  433. if (!retry_with_timeout([&]() { return m_registers->interrupt_status.command_complete; })) {
  434. return EIO;
  435. }
  436. // 7. Write 1 to the Command Complete in the Normal Interrupt Status
  437. // register for clearing this bit.
  438. m_registers->interrupt_status.raw = command_complete;
  439. // 8. Read Response register and get necessary information of the issued
  440. // command
  441. // (FIXME: Return the value for better error handling)
  442. // 9. In the case where this sequence is for write to a card, go to step
  443. // (10).
  444. // In case of read from a card, go to step (14).
  445. if (data_transfer_type == DataTransferType::Write) {
  446. for (u32 i = 0; i < block_count; i++) {
  447. // 10. Then wait for Buffer Write Ready Interrupt.
  448. if (!retry_with_timeout(
  449. [&]() {
  450. return m_registers->interrupt_status.buffer_write_ready;
  451. })) {
  452. return EIO;
  453. }
  454. // 11. Write 1 to the Buffer Write Ready in the Normal Interrupt Status register for clearing this bit.
  455. m_registers->interrupt_status.raw = buffer_write_ready;
  456. // 12. Write block data (in according to the number of bytes specified at the step (1)) to Buffer Data Port register.
  457. u32 temp;
  458. for (u32 j = 0; j < block_size / sizeof(u32); j++) {
  459. TRY(buf.read(&temp, i * block_size + sizeof(u32) * j, sizeof(u32)));
  460. m_registers->buffer_data_port = temp;
  461. }
  462. // 13. Repeat until all blocks are sent and then go to step (18).
  463. }
  464. } else {
  465. for (u32 i = 0; i < block_count; i++) {
  466. // 14. Then wait for the Buffer Read Ready Interrupt.
  467. if (!retry_with_timeout([&]() { return m_registers->interrupt_status.buffer_read_ready; })) {
  468. return EIO;
  469. }
  470. // 15. Write 1 to the Buffer Read Ready in the Normal Interrupt Status
  471. // register for clearing this bit.
  472. m_registers->interrupt_status.raw = buffer_read_ready;
  473. // 16. Read block data (in according to the number of bytes specified at
  474. // the step (1)) from the Buffer Data Port register
  475. u32 temp;
  476. for (u32 j = 0; j < block_size / sizeof(u32); j++) {
  477. temp = m_registers->buffer_data_port;
  478. TRY(buf.write(&temp, i * block_size + sizeof(u32) * j, sizeof(u32)));
  479. }
  480. // 17. Repeat until all blocks are received and then go to step (18).
  481. }
  482. }
  483. // 18. If this sequence is for Single or Multiple Block Transfer, go to step
  484. // (19). In case of Infinite Block Transfer, go to step (21)
  485. // 19. Wait for Transfer Complete Interrupt.
  486. if (!retry_with_timeout(
  487. [&]() { return m_registers->interrupt_status.transfer_complete; })) {
  488. return EIO;
  489. }
  490. // 20. Write 1 to the Transfer Complete in the Normal Interrupt Status
  491. // register for clearing this bit
  492. m_registers->interrupt_status.raw = transfer_complete;
  493. return {};
  494. }
  495. u32 SDHostController::make_adma_descriptor_table(u32 block_count)
  496. {
  497. // FIXME: We might be able to write to the destination buffer directly
  498. // Especially with 64 bit addressing enabled
  499. // This might cost us more descriptor entries but avoids the memcpy at the end
  500. // of each read cycle
  501. FlatPtr adma_descriptor_physical = m_dma_region->physical_page(0)->paddr().get();
  502. FlatPtr adma_dma_region_physical = adma_descriptor_physical + PAGE_SIZE;
  503. FlatPtr adma_descriptor_virtual = m_dma_region->vaddr().get();
  504. u32 offset = 0;
  505. u32 blocks_transferred = 0;
  506. u32 blocks_per_descriptor = (1 << 16) / block_len;
  507. using enum OperatingMode;
  508. switch (m_mode) {
  509. case ADMA2_32: {
  510. u32 i = 0;
  511. Array<SD::DMADescriptor64, 64>& command_buffer = *bit_cast<Array<SD::DMADescriptor64, 64>*>(adma_descriptor_virtual);
  512. for (; i < 64; ++i) {
  513. FlatPtr physical_transfer_address = adma_dma_region_physical + offset;
  514. VERIFY(physical_transfer_address >> 32 == 0);
  515. // If the remaining block count is less than the maximum addressable blocks
  516. // we need to set the actual length and break out of the loop
  517. if (block_count - blocks_transferred < blocks_per_descriptor) {
  518. u32 blocks_to_transfer = block_count - blocks_transferred;
  519. command_buffer[i] = SD::DMADescriptor64 {
  520. .valid = 1,
  521. .end = 1,
  522. .interrupt = 0,
  523. .action = SD::DMAAction::Tran,
  524. .length_upper = 0,
  525. .length_lower = static_cast<u32>(blocks_to_transfer * block_len),
  526. .address = static_cast<u32>(physical_transfer_address),
  527. };
  528. blocks_transferred += blocks_to_transfer;
  529. offset += static_cast<size_t>(blocks_to_transfer) * block_len;
  530. break;
  531. }
  532. command_buffer[i] = SD::DMADescriptor64 {
  533. .valid = 1,
  534. .end = 0,
  535. .interrupt = 0,
  536. .action = SD::DMAAction::Tran,
  537. .length_upper = 0,
  538. .length_lower = 0, // length of 0 means 1<<16 bytes
  539. .address = static_cast<u32>(physical_transfer_address),
  540. };
  541. blocks_transferred += blocks_per_descriptor;
  542. offset += (1 << 16);
  543. }
  544. command_buffer[min(i, 63)].end = 1;
  545. break;
  546. }
  547. case ADMA2_64: {
  548. u32 i = 0;
  549. Array<SD::DMADescriptor128, 32>& command_buffer = *bit_cast<Array<SD::DMADescriptor128, 32>*>(adma_descriptor_virtual);
  550. for (; i < 32; ++i) {
  551. FlatPtr physical_transfer_address = adma_dma_region_physical + offset;
  552. VERIFY(physical_transfer_address >> 32 == 0);
  553. // If the remaining block count is less than the maximum addressable blocks
  554. // we need to set the actual length and break out of the loop
  555. if (block_count - blocks_transferred < blocks_per_descriptor) {
  556. u32 blocks_to_read = block_count - blocks_transferred;
  557. command_buffer[i] = SD::DMADescriptor128 {
  558. .valid = 1,
  559. .end = 1,
  560. .interrupt = 0,
  561. .action = SD::DMAAction::Tran,
  562. .length_upper = 0,
  563. .length_lower = static_cast<u32>(blocks_to_read * block_len),
  564. .address_low = static_cast<u32>((physical_transfer_address + offset) & 0xFFFF'FFFF),
  565. .address_high = static_cast<u32>((physical_transfer_address + offset) >> 32),
  566. };
  567. blocks_transferred += blocks_to_read;
  568. offset += static_cast<size_t>(blocks_to_read) * block_len;
  569. break;
  570. }
  571. command_buffer[i] = SD::DMADescriptor128 {
  572. .valid = 1,
  573. .end = 0,
  574. .interrupt = 0,
  575. .action = SD::DMAAction::Tran,
  576. .length_upper = 0,
  577. .length_lower = 0, // length of 0 means 1<<16 bytes
  578. .address_low = static_cast<u32>((physical_transfer_address + offset) & 0xFFFF'FFFF),
  579. .address_high = static_cast<u32>((physical_transfer_address + offset) >> 32),
  580. };
  581. blocks_transferred += blocks_per_descriptor;
  582. offset += (1 << 16);
  583. }
  584. command_buffer[min(i, 31)].end = 1;
  585. break;
  586. }
  587. case PIO:
  588. VERIFY_NOT_REACHED();
  589. }
  590. return blocks_transferred;
  591. }
  592. ErrorOr<void> SDHostController::transfer_blocks_adma2(u32 block_address, u32 block_count, UserOrKernelBuffer out, SD::DataTransferDirection direction)
  593. {
  594. using enum OperatingMode;
  595. FlatPtr adma_descriptor_physical = m_dma_region->physical_page(0)->paddr().get();
  596. FlatPtr adma_descriptor_virtual = m_dma_region->vaddr().get();
  597. FlatPtr adma_dma_region_virtual = adma_descriptor_virtual + PAGE_SIZE;
  598. AK::ArmedScopeGuard abort_guard {
  599. [] {
  600. dbgln("Aborting SDHC ADMA read");
  601. TODO();
  602. }
  603. };
  604. // 3.7.2.3 Using ADMA
  605. u32 blocks_per_descriptor = (1 << 16) / block_len;
  606. u32 addressable_blocks_per_transfer = blocks_per_descriptor * (m_mode == ADMA2_32 ? 64 : 32);
  607. size_t host_offset = 0;
  608. size_t card_offset = 0;
  609. u32 blocks_transferred_total = 0;
  610. while (blocks_transferred_total < block_count) {
  611. // When writing to the card we must prime the transfer buffer with the data we want to write
  612. // FIXME: We might be able to transfer to/from the destination/origin buffer directly
  613. // Especially with 64 bit addressing enabled
  614. // This might cost us more descriptor entries, when the physical range is segmented,
  615. // but avoids the memcpy at the end of each transfer cycle
  616. if (direction == SD::DataTransferDirection::HostToCard)
  617. TRY(out.read(bit_cast<void*>(adma_dma_region_virtual), host_offset, min(block_count - blocks_transferred_total, addressable_blocks_per_transfer) * block_len));
  618. // (1) Create Descriptor table for ADMA in the system memory
  619. u32 blocks_transferred = make_adma_descriptor_table(block_count);
  620. card_offset += blocks_transferred * block_len;
  621. // (2) Set the Descriptor address for ADMA in the ADMA System Address register.
  622. m_registers->adma_system_address[0] = static_cast<u32>(adma_descriptor_physical & 0xFFFF'FFFF);
  623. if (m_mode == ADMA2_64)
  624. m_registers->adma_system_address[1] = static_cast<u32>(adma_descriptor_physical >> 32);
  625. // (3) Set the value corresponding to the executed data byte length of one block in the Block Size
  626. // register.
  627. // (4) Set the value corresponding to the executed data block count in the Block Count register in
  628. // accordance with Table 2-9. Refer to Section 1.15 for more details.
  629. // Note: To avoid the restriction of the 16 bit block count we disable the block counter
  630. // and do not set the block count, resulting in an "Infinite Transfer" (SDHC Table 2-9)
  631. // ADMA has its own way of encoding block counts and to signal transfer termination
  632. m_registers->block_size_and_block_count = block_len;
  633. // (5) Set the argument value to the Argument register.
  634. m_registers->argument_1 = block_address;
  635. // (6) Set the value to the Transfer Mode register. The Host Driver determines Multi / Single Block
  636. // Select, Block Count Enable, Data Transfer Direction, Auto CMD12 Enable and DMA
  637. // Enable. Multi / Single Block Select and Block Count Enable are determined according to
  638. // Table 2-9.
  639. // If response check is enabled (Response Error Check Enable =1), set Response Interrupt
  640. // Disable to 1 and select Response Type R1 / R5
  641. SD::Command command = {
  642. .dma_enable = 1,
  643. .block_counter = 0,
  644. .auto_command = blocks_transferred > 1 ? SD::SendAutoCommand::Command12 : SD::SendAutoCommand::Disabled,
  645. .direction = direction,
  646. .multiblock = blocks_transferred > 1,
  647. .response_type_r1r5 = 0,
  648. .response_error_check = 0,
  649. .response_interrupt_disable = 0,
  650. .reserved1 = 0,
  651. .response_type = SD::ResponseType::ResponseOf48Bits,
  652. .sub_command_flag = 0,
  653. .crc_enable = 1,
  654. .idx_enable = 0,
  655. .is_data = 1,
  656. .type = SD::CommandType::Normal,
  657. .index = direction == SD::DataTransferDirection::HostToCard ? (blocks_transferred > 1 ? SD::CommandIndex::WriteMultipleBlock : SD::CommandIndex::WriteSingleBlock)
  658. : (blocks_transferred > 1 ? SD::CommandIndex::ReadMultipleBlock : SD::CommandIndex::ReadSingleBlock),
  659. .reserved3 = 0
  660. };
  661. // (7) Set the value to the Command register.
  662. // Note: When writing to the upper byte [3] of the Command register, the SD command is issued
  663. // and DMA is started.
  664. m_registers->transfer_mode_and_command = command.raw;
  665. // (8) If response check is enabled, go to stop (11) else wait for the Command Complete Interrupt.
  666. // Note: We never enabled response checking
  667. if (!retry_with_timeout([this]() { return m_registers->interrupt_status.command_complete; })) {
  668. dbgln("SDHC: ADMA2 command response timed out");
  669. }
  670. // (9) Write 1 to the Command Complete in the Normal Interrupt Status register to clear this bit.
  671. // Note: We cannot write to the nit field member directly, due to that also possibly
  672. // setting the already completed `transfer_complete` flag, making the next check time out.
  673. m_registers->interrupt_status.raw = command_complete;
  674. // TODO: (10) Read Response register and get necessary information of the issued command
  675. // (11) Wait for the Transfer Complete Interrupt and ADMA Error Interrupt.
  676. // FIXME: Especially with big transfers this might timeout before the transfer is finished, although
  677. // No error has has happened
  678. // We should set this up so that it actually waits for the interrupts via a designated handler
  679. // Note, that the SDHC has a way to detect transfer timeouts on its own
  680. if (!retry_with_timeout([this]() { return m_registers->interrupt_status.transfer_complete || m_registers->interrupt_status.adma_error; })) {
  681. dbgln("SDHC: ADMA2 transfer timed out");
  682. return EIO;
  683. }
  684. // (12) If Transfer Complete is set to 1, go to Step (13)
  685. if (m_registers->interrupt_status.transfer_complete) {
  686. // (13) Write 1 to the Transfer Complete Status in the Normal Interrupt Status register to clear this bit.
  687. m_registers->interrupt_status.transfer_complete = 1;
  688. }
  689. // else if ADMA Error Interrupt is set to 1, go to Step (14).
  690. else if (m_registers->interrupt_status.adma_error) {
  691. // (14) Write 1 to the ADMA Error Interrupt Status in the Error Interrupt Status register to clear this bit.
  692. m_registers->interrupt_status.adma_error = 1;
  693. // (15) Abort ADMA operation. SD card operation should be stopped by issuing abort command. If
  694. // necessary, the Host Driver checks ADMA Error Status register to detect why ADMA error is
  695. // generated
  696. dmesgln("SDHC transfer failed, ADMA Error Status: {:2b}", AK::to_underlying(m_registers->adma_error_status.state));
  697. // The scope guard will handle the Abort
  698. return EIO;
  699. } else {
  700. VERIFY_NOT_REACHED();
  701. }
  702. // Copy the read data to the correct memory location
  703. // FIXME: As described above, we may be able to target the destination buffer directly
  704. if (direction == SD::DataTransferDirection::CardToHost)
  705. TRY(out.write(bit_cast<void const*>(adma_dma_region_virtual), host_offset, blocks_transferred * block_len));
  706. blocks_transferred_total += blocks_transferred;
  707. host_offset = card_offset;
  708. block_address += card_offset;
  709. card_offset = 0;
  710. }
  711. abort_guard.disarm();
  712. return {};
  713. }
  714. ErrorOr<void> SDHostController::read_block(Badge<SDMemoryCard>, u32 block_address, u32 block_count, UserOrKernelBuffer out)
  715. {
  716. VERIFY(is_card_inserted());
  717. using enum OperatingMode;
  718. switch (m_mode) {
  719. case OperatingMode::ADMA2_32:
  720. case OperatingMode::ADMA2_64:
  721. return transfer_blocks_adma2(block_address, block_count, out, SD::DataTransferDirection::CardToHost);
  722. case PIO: {
  723. if (block_count > 1) {
  724. return transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  725. SD::Commands::read_multiple_block,
  726. block_address,
  727. block_count,
  728. block_len,
  729. out,
  730. DataTransferType::Read);
  731. }
  732. return transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  733. SD::Commands::read_single_block,
  734. block_address,
  735. block_count,
  736. block_len,
  737. out,
  738. DataTransferType::Read);
  739. }
  740. default:
  741. VERIFY_NOT_REACHED();
  742. }
  743. }
  744. ErrorOr<void> SDHostController::write_block(Badge<SDMemoryCard>, u32 block_address, u32 block_count, UserOrKernelBuffer in)
  745. {
  746. VERIFY(is_card_inserted());
  747. using enum OperatingMode;
  748. switch (m_mode) {
  749. case OperatingMode::ADMA2_32:
  750. case OperatingMode::ADMA2_64:
  751. return transfer_blocks_adma2(block_address, block_count, in, SD::DataTransferDirection::HostToCard);
  752. case PIO: {
  753. if (block_count > 1) {
  754. return transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  755. SD::Commands::write_multiple_block,
  756. block_address,
  757. block_count,
  758. block_len,
  759. in,
  760. DataTransferType::Write);
  761. }
  762. return transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  763. SD::Commands::write_single_block,
  764. block_address,
  765. block_count,
  766. block_len,
  767. in,
  768. DataTransferType::Write);
  769. }
  770. default:
  771. VERIFY_NOT_REACHED();
  772. };
  773. }
  774. ErrorOr<SD::SDConfigurationRegister> SDHostController::retrieve_sd_configuration_register(u32 relative_card_address)
  775. {
  776. SD::SDConfigurationRegister scr;
  777. TRY(issue_command(SD::Commands::app_cmd, relative_card_address));
  778. TRY(wait_for_response());
  779. TRY(transaction_control_with_data_transfer_using_the_dat_line_without_dma(
  780. SD::Commands::app_send_scr,
  781. 0, 1, 8,
  782. UserOrKernelBuffer::for_kernel_buffer(scr.raw), DataTransferType::Read));
  783. return scr;
  784. }
  785. ErrorOr<u32> SDHostController::retrieve_sd_clock_frequency()
  786. {
  787. if (m_registers->capabilities.base_clock_frequency == 0) {
  788. // Spec says:
  789. // If these bits are all 0, the Host System has to get information via another method
  790. TODO();
  791. }
  792. const i64 one_mhz = 1'000'000;
  793. return { m_registers->capabilities.base_clock_frequency * one_mhz };
  794. }
  795. // PLSS Table 4-43 : Card Status Field/Command
  796. bool SDHostController::card_status_contains_errors(SD::Command const& command, u32 resp)
  797. {
  798. SD::CardStatus status;
  799. // PLSS 4.9.5 R6
  800. if (command.index == SD::CommandIndex::SendRelativeAddr) {
  801. status.raw = (resp & 0x1fff) | ((resp & 0x2000) << 6) | ((resp & 0x4000) << 8) | ((resp & 0x8000) << 8);
  802. } else {
  803. status.raw = resp;
  804. }
  805. 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;
  806. bool contains_errors = false;
  807. switch (command.index) {
  808. case SD::CommandIndex::SendRelativeAddr:
  809. if (status.error || status.illegal_command || status.com_crc_error) {
  810. contains_errors = true;
  811. }
  812. break;
  813. case SD::CommandIndex::SelectCard:
  814. if (common_errors) {
  815. contains_errors = true;
  816. }
  817. break;
  818. case SD::CommandIndex::SetBlockLen:
  819. if (common_errors || status.block_len_error) {
  820. contains_errors = true;
  821. }
  822. break;
  823. case SD::CommandIndex::ReadSingleBlock:
  824. case SD::CommandIndex::ReadMultipleBlock:
  825. if (common_errors || status.address_error || status.out_of_range) {
  826. contains_errors = true;
  827. }
  828. break;
  829. case SD::CommandIndex::WriteSingleBlock:
  830. case SD::CommandIndex::WriteMultipleBlock:
  831. if (common_errors || status.block_len_error || status.address_error || status.out_of_range) {
  832. contains_errors = true;
  833. }
  834. break;
  835. case SD::CommandIndex::AppSendScr:
  836. if (common_errors) {
  837. contains_errors = true;
  838. }
  839. break;
  840. case SD::CommandIndex::AppCmd:
  841. if (common_errors) {
  842. contains_errors = true;
  843. }
  844. break;
  845. default:
  846. break;
  847. }
  848. return contains_errors;
  849. }
  850. }