SDHostController.cpp 41 KB

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