SDHostController.cpp 42 KB

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