1 /* 2 * Copyright 2018-2020 Haiku, Inc. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * B Krishnan Iyer, krishnaniyer97@gmail.com 7 * Adrien Destugues, pulkomandy@pulkomandy.tk 8 */ 9 #include <algorithm> 10 #include <new> 11 #include <stdio.h> 12 #include <string.h> 13 14 #include <bus/PCI.h> 15 #include <PCI_x86.h> 16 17 #include <KernelExport.h> 18 19 #include "IOSchedulerSimple.h" 20 #include "mmc.h" 21 #include "sdhci_pci.h" 22 23 24 #define TRACE_SDHCI 25 #ifdef TRACE_SDHCI 26 # define TRACE(x...) dprintf("\33[33msdhci_pci:\33[0m " x) 27 #else 28 # define TRACE(x...) ; 29 #endif 30 #define TRACE_ALWAYS(x...) dprintf("\33[33msdhci_pci:\33[0m " x) 31 #define ERROR(x...) dprintf("\33[33msdhci_pci:\33[0m " x) 32 #define CALLED(x...) TRACE("CALLED %s\n", __PRETTY_FUNCTION__) 33 34 35 #define SDHCI_PCI_DEVICE_MODULE_NAME "busses/mmc/sdhci_pci/driver_v1" 36 #define SDHCI_PCI_MMC_BUS_MODULE_NAME "busses/mmc/sdhci_pci/device/v1" 37 38 #define SLOT_NUMBER "device/slot" 39 #define BAR_INDEX "device/bar" 40 41 42 class SdhciBus { 43 public: 44 SdhciBus(struct registers* registers, uint8_t irq); 45 ~SdhciBus(); 46 47 void EnableInterrupts(uint32_t mask); 48 void DisableInterrupts(); 49 status_t ExecuteCommand(uint8_t command, uint32_t argument, 50 uint32_t* response); 51 int32 HandleInterrupt(); 52 status_t InitCheck(); 53 void Reset(); 54 void SetClock(int kilohertz); 55 status_t DoIO(uint8_t command, IOOperation* operation, 56 bool offsetAsSectors); 57 void SetScanSemaphore(sem_id sem); 58 void SetBusWidth(int width); 59 60 private: 61 bool PowerOn(); 62 void RecoverError(); 63 64 private: 65 struct registers* fRegisters; 66 uint32_t fCommandResult; 67 uint8_t fIrq; 68 sem_id fSemaphore; 69 sem_id fScanSemaphore; 70 status_t fStatus; 71 }; 72 73 74 class SdhciDevice { 75 public: 76 device_node* fNode; 77 uint8_t fRicohOriginalMode; 78 }; 79 80 81 device_manager_info* gDeviceManager; 82 device_module_info* gMMCBusController; 83 84 85 static int32 86 sdhci_generic_interrupt(void* data) 87 { 88 SdhciBus* bus = (SdhciBus*)data; 89 return bus->HandleInterrupt(); 90 } 91 92 93 SdhciBus::SdhciBus(struct registers* registers, uint8_t irq) 94 : 95 fRegisters(registers), 96 fIrq(irq), 97 fSemaphore(0) 98 { 99 if (irq == 0 || irq == 0xff) { 100 ERROR("PCI IRQ not assigned\n"); 101 fStatus = B_BAD_DATA; 102 return; 103 } 104 105 fSemaphore = create_sem(0, "SDHCI interrupts"); 106 107 DisableInterrupts(); 108 109 fStatus = install_io_interrupt_handler(fIrq, 110 sdhci_generic_interrupt, this, 0); 111 112 if (fStatus != B_OK) { 113 ERROR("can't install interrupt handler\n"); 114 return; 115 } 116 117 // First of all, we have to make sure we are in a sane state. The easiest 118 // way is to reset everything. 119 Reset(); 120 121 // Turn on the power supply to the card, if there is a card inserted 122 if (PowerOn()) { 123 // Then we configure the clock to the frequency needed for 124 // initialization 125 SetClock(400); 126 } 127 128 // Finally, configure some useful interrupts 129 EnableInterrupts(SDHCI_INT_CMD_CMP | SDHCI_INT_CARD_REM 130 | SDHCI_INT_TRANS_CMP); 131 132 // We want to see the error bits in the status register, but not have an 133 // interrupt trigger on them (we get a "command complete" interrupt on 134 // errors already) 135 fRegisters->interrupt_status_enable |= SDHCI_INT_ERROR 136 | SDHCI_INT_TIMEOUT | SDHCI_INT_CRC | SDHCI_INT_INDEX 137 | SDHCI_INT_BUS_POWER | SDHCI_INT_END_BIT; 138 } 139 140 141 SdhciBus::~SdhciBus() 142 { 143 DisableInterrupts(); 144 145 if (fSemaphore != 0) 146 delete_sem(fSemaphore); 147 148 if (fIrq != 0) 149 remove_io_interrupt_handler(fIrq, sdhci_generic_interrupt, this); 150 151 area_id regs_area = area_for(fRegisters); 152 delete_area(regs_area); 153 } 154 155 156 void 157 SdhciBus::EnableInterrupts(uint32_t mask) 158 { 159 fRegisters->interrupt_status_enable |= mask; 160 fRegisters->interrupt_signal_enable |= mask; 161 } 162 163 164 void 165 SdhciBus::DisableInterrupts() 166 { 167 fRegisters->interrupt_status_enable = 0; 168 fRegisters->interrupt_signal_enable = 0; 169 } 170 171 172 // #pragma mark - 173 /* 174 PartA2, SD Host Controller Simplified Specification, Version 4.20 175 §3.7.1.1 The sequence to issue an SD Command 176 */ 177 status_t 178 SdhciBus::ExecuteCommand(uint8_t command, uint32_t argument, uint32_t* response) 179 { 180 TRACE("ExecuteCommand(%d, %x)\n", command, argument); 181 182 // First of all clear the result 183 fCommandResult = 0; 184 185 // Check if it's possible to send a command right now. 186 // It is not possible to send a command as long as the command line is busy. 187 // The spec says we should wait, but we can't do that on kernel side, since 188 // it leaves no chance for the upper layers to handle the problem. So we 189 // just say we're busy and the caller can retry later. 190 // Note that this should normally never happen: the command line is busy 191 // only during command execution, and we don't leave this function with ac 192 // command running. 193 if (fRegisters->present_state.CommandInhibit()) { 194 panic("Command execution impossible, command inhibit\n"); 195 return B_BUSY; 196 } 197 if (fRegisters->present_state.DataInhibit()) { 198 panic("Command execution unwise, data inhibit\n"); 199 return B_BUSY; 200 } 201 202 uint32_t replyType; 203 204 switch (command) { 205 case SD_GO_IDLE_STATE: 206 replyType = Command::kNoReplyType; 207 break; 208 case SD_ALL_SEND_CID: 209 case SD_SEND_CSD: 210 replyType = Command::kR2Type; 211 break; 212 case SD_SEND_RELATIVE_ADDR: 213 replyType = Command::kR6Type; 214 break; 215 case SD_SELECT_DESELECT_CARD: 216 case SD_ERASE: 217 replyType = Command::kR1bType; 218 break; 219 case SD_SEND_IF_COND: 220 replyType = Command::kR7Type; 221 break; 222 case SD_READ_SINGLE_BLOCK: 223 case SD_READ_MULTIPLE_BLOCKS: 224 case SD_WRITE_SINGLE_BLOCK: 225 case SD_WRITE_MULTIPLE_BLOCKS: 226 replyType = Command::kR1Type | Command::kDataPresent; 227 break; 228 case SD_APP_CMD: 229 case SD_ERASE_WR_BLK_START: 230 case SD_ERASE_WR_BLK_END: 231 case SD_SET_BUS_WIDTH: // SD Application command 232 replyType = Command::kR1Type; 233 break; 234 case SD_SEND_OP_COND: // SD Application command 235 replyType = Command::kR3Type; 236 break; 237 default: 238 ERROR("Unknown command %x\n", command); 239 return B_BAD_DATA; 240 } 241 242 // Check if DATA line is available (if needed) 243 if ((replyType & Command::k32BitResponseCheckBusy) != 0 244 && command != SD_STOP_TRANSMISSION && command != SD_IO_ABORT) { 245 if (fRegisters->present_state.DataInhibit()) { 246 ERROR("Execution aborted, data inhibit\n"); 247 return B_BUSY; 248 } 249 } 250 251 if (fRegisters->present_state.CommandInhibit()) 252 panic("Command line busy at start of execute command\n"); 253 254 if (replyType == Command::kR1bType) 255 fRegisters->transfer_mode = 0; 256 257 fRegisters->argument = argument; 258 fRegisters->command.SendCommand(command, replyType); 259 260 // Wait for command response to be available ("command complete" interrupt) 261 TRACE("Wait for command complete..."); 262 do { 263 acquire_sem(fSemaphore); 264 TRACE("command complete sem acquired, status: %x\n", fCommandResult); 265 TRACE("real status = %x command line busy: %d\n", 266 fRegisters->interrupt_status, 267 fRegisters->present_state.CommandInhibit()); 268 } while (fCommandResult == 0); 269 270 TRACE("Command response available\n"); 271 272 if (fCommandResult & SDHCI_INT_ERROR) { 273 fRegisters->interrupt_status |= fCommandResult; 274 if (fCommandResult & SDHCI_INT_TIMEOUT) { 275 ERROR("Command execution timed out\n"); 276 if (fRegisters->present_state.CommandInhibit()) { 277 TRACE("Command line is still busy, clearing it\n"); 278 // Clear the stall 279 fRegisters->software_reset.ResetCommandLine(); 280 } 281 return B_TIMED_OUT; 282 } 283 if (fCommandResult & SDHCI_INT_CRC) { 284 ERROR("CRC error\n"); 285 return B_BAD_VALUE; 286 } 287 ERROR("Command execution failed %x\n", fCommandResult); 288 // TODO look at errors in interrupt_status register for more details 289 // and return a more appropriate error code 290 return B_ERROR; 291 } 292 293 if (fRegisters->present_state.CommandInhibit()) { 294 TRACE("Command execution failed, card stalled\n"); 295 // Clear the stall 296 fRegisters->software_reset.ResetCommandLine(); 297 return B_ERROR; 298 } 299 300 switch (replyType & Command::kReplySizeMask) { 301 case Command::k32BitResponse: 302 *response = fRegisters->response[0]; 303 break; 304 case Command::k128BitResponse: 305 response[0] = fRegisters->response[0]; 306 response[1] = fRegisters->response[1]; 307 response[2] = fRegisters->response[2]; 308 response[3] = fRegisters->response[3]; 309 break; 310 311 default: 312 // No response 313 break; 314 } 315 316 if (replyType == Command::kR1bType 317 && (fCommandResult & SDHCI_INT_TRANS_CMP) == 0) { 318 // R1b commands may use the data line so we must wait for the 319 // "transfer complete" interrupt here. 320 TRACE("Waiting for data line...\n"); 321 do { 322 acquire_sem(fSemaphore); 323 } while (fRegisters->present_state.DataInhibit()); 324 TRACE("Dataline is released.\n"); 325 } 326 327 ERROR("Command execution %d complete\n", command); 328 return B_OK; 329 } 330 331 332 status_t 333 SdhciBus::InitCheck() 334 { 335 return fStatus; 336 } 337 338 339 void 340 SdhciBus::Reset() 341 { 342 if (!fRegisters->software_reset.ResetAll()) 343 ERROR("SdhciBus::Reset: SoftwareReset timeout\n"); 344 } 345 346 347 void 348 SdhciBus::SetClock(int kilohertz) 349 { 350 int base_clock = fRegisters->capabilities.BaseClockFrequency(); 351 // Try to get as close to 400kHz as possible, but not faster 352 int divider = base_clock * 1000 / kilohertz; 353 354 if (fRegisters->host_controller_version.specVersion <= 1) { 355 // Old controller only support power of two dividers up to 256, 356 // round to next power of two up to 256 357 if (divider > 256) 358 divider = 256; 359 360 divider--; 361 divider |= divider >> 1; 362 divider |= divider >> 2; 363 divider |= divider >> 4; 364 divider++; 365 } 366 367 divider = fRegisters->clock_control.SetDivider(divider); 368 369 // Log the value after possible rounding by SetDivider (only even values 370 // are allowed). 371 TRACE("SDCLK frequency: %dMHz / %d = %dkHz\n", base_clock, divider, 372 base_clock * 1000 / divider); 373 374 // We have set the divider, now we can enable the internal clock. 375 fRegisters->clock_control.EnableInternal(); 376 377 // wait until internal clock is stabilized 378 while (!(fRegisters->clock_control.InternalStable())); 379 380 fRegisters->clock_control.EnablePLL(); 381 while (!(fRegisters->clock_control.InternalStable())); 382 383 // Finally, route the clock to the SD card 384 fRegisters->clock_control.EnableSD(); 385 } 386 387 388 status_t 389 SdhciBus::DoIO(uint8_t command, IOOperation* operation, bool offsetAsSectors) 390 { 391 bool isWrite = operation->IsWrite(); 392 393 static const uint32 kBlockSize = 512; 394 off_t offset = operation->Offset(); 395 generic_size_t length = operation->Length(); 396 397 TRACE("%s %" B_PRIu64 " bytes at %" B_PRIdOFF "\n", 398 isWrite ? "Write" : "Read", length, offset); 399 400 // Check that the IO scheduler did its job in following our DMA restrictions 401 // We can start a read only at a sector boundary 402 ASSERT(offset % kBlockSize == 0); 403 // We can only read complete sectors 404 ASSERT(length % kBlockSize == 0); 405 406 const generic_io_vec* vecs = operation->Vecs(); 407 generic_size_t vecOffset = 0; 408 409 // FIXME can this be moved to the init function instead? 410 // 411 // For simplicity we use a transfer size equal to the sector size. We could 412 // go up to 2K here if the length to read in each individual vec is a 413 // multiple of 2K, but we have no easy way to know this (we would need to 414 // iterate through the IOOperation vecs and check the size of each of them). 415 // We could also do smaller transfers, but it is not possible to start a 416 // transfer anywhere else than the start of a sector, so it's a lot simpler 417 // to always work in complete sectors. We set the B_DMA_ALIGNMENT device 418 // node property accordingly, making sure that we don't get asked to do 419 // transfers that are not aligned with sectors. 420 // 421 // Additionnally, set SDMA buffer boundary aligment to 512K. This is the 422 // largest possible size. We also set the B_DMA_BOUNDARY property on the 423 // published device node, so that the DMA resource manager knows that it 424 // must respect this boundary. As a result, we will never be asked to 425 // do a transfer that crosses this boundary, and we don't need to handle 426 // the DMA boundary interrupt (the transfer will be split in two at an 427 // upper layer). 428 fRegisters->block_size.ConfigureTransfer(kBlockSize, 429 BlockSize::kDmaBoundary512K); 430 status_t result = B_OK; 431 432 while (length > 0) { 433 size_t toCopy = std::min((generic_size_t)length, 434 vecs->length - vecOffset); 435 436 // If the current vec is empty, we can move to the next 437 if (toCopy == 0) { 438 vecs++; 439 vecOffset = 0; 440 continue; 441 } 442 443 // With SDMA we can only transfer multiples of 1 sector 444 ASSERT(toCopy % kBlockSize == 0); 445 446 fRegisters->system_address = vecs->base + vecOffset; 447 // fRegisters->adma_system_address = fDmaMemory; 448 449 fRegisters->block_count = toCopy / kBlockSize; 450 451 uint16 direction; 452 if (isWrite) 453 direction = TransferMode::kWrite; 454 else 455 direction = TransferMode::kRead; 456 fRegisters->transfer_mode = TransferMode::kMulti | direction 457 | TransferMode::kAutoCmd12Enable 458 | TransferMode::kBlockCountEnable | TransferMode::kDmaEnable; 459 460 uint32_t response; 461 result = ExecuteCommand(command, 462 offset / (offsetAsSectors ? kBlockSize : 1), &response); 463 if (result != B_OK) 464 break; 465 466 // Wait for DMA transfer to complete 467 // In theory we could go on and send other commands as long as they 468 // don't need the DAT lines, but it's overcomplicating things. 469 TRACE("Wait for transfer complete..."); 470 acquire_sem(fSemaphore); 471 TRACE("transfer complete OK.\n"); 472 473 length -= toCopy; 474 vecOffset += toCopy; 475 offset += toCopy; 476 } 477 478 return result; 479 } 480 481 482 void 483 SdhciBus::SetScanSemaphore(sem_id sem) 484 { 485 fScanSemaphore = sem; 486 487 // If there is already a card in, start a scan immediately 488 if (fRegisters->present_state.IsCardInserted()) 489 release_sem(fScanSemaphore); 490 491 // We can now enable the card insertion interrupt for next time a card 492 // is inserted 493 EnableInterrupts(SDHCI_INT_CARD_INS); 494 } 495 496 497 void 498 SdhciBus::SetBusWidth(int width) 499 { 500 uint8_t widthBits; 501 switch(width) { 502 case 1: 503 widthBits = HostControl::kDataTransfer1Bit; 504 break; 505 case 4: 506 widthBits = HostControl::kDataTransfer4Bit; 507 break; 508 case 8: 509 widthBits = HostControl::kDataTransfer8Bit; 510 break; 511 default: 512 panic("Incorrect bitwidth value"); 513 return; 514 } 515 fRegisters->host_control.SetDataTransferWidth(widthBits); 516 } 517 518 519 bool 520 SdhciBus::PowerOn() 521 { 522 if (!fRegisters->present_state.IsCardInserted()) { 523 TRACE("Card not inserted, not powering on for now\n"); 524 return false; 525 } 526 527 uint8_t supportedVoltages = fRegisters->capabilities.SupportedVoltages(); 528 if ((supportedVoltages & Capabilities::k3v3) != 0) 529 fRegisters->power_control.SetVoltage(PowerControl::k3v3); 530 else if ((supportedVoltages & Capabilities::k3v0) != 0) 531 fRegisters->power_control.SetVoltage(PowerControl::k3v0); 532 else if ((supportedVoltages & Capabilities::k1v8) != 0) 533 fRegisters->power_control.SetVoltage(PowerControl::k1v8); 534 else { 535 fRegisters->power_control.PowerOff(); 536 ERROR("No voltage is supported\n"); 537 return false; 538 } 539 540 return true; 541 } 542 543 544 void 545 SdhciBus::RecoverError() 546 { 547 fRegisters->interrupt_signal_enable &= ~(SDHCI_INT_CMD_CMP 548 | SDHCI_INT_TRANS_CMP | SDHCI_INT_CARD_INS | SDHCI_INT_CARD_REM); 549 550 if (fRegisters->interrupt_status & 7) 551 fRegisters->software_reset.ResetCommandLine(); 552 553 int16_t error_status = fRegisters->interrupt_status; 554 fRegisters->interrupt_status &= ~(error_status); 555 } 556 557 558 int32 559 SdhciBus::HandleInterrupt() 560 { 561 #if 0 562 // We could use the slot register to quickly see for which slot the 563 // interrupt is. But since we have an interrupt handler call for each slot 564 // anyway, it's just as simple to let each of them scan its own interrupt 565 // status register. 566 if ( !(fRegisters->slot_interrupt_status & (1 << fSlot)) ) { 567 TRACE("interrupt not for me.\n"); 568 return B_UNHANDLED_INTERRUPT; 569 } 570 #endif 571 572 uint32_t intmask = fRegisters->interrupt_status; 573 574 // Shortcut: exit early if there is no interrupt or if the register is 575 // clearly invalid. 576 if ((intmask == 0) || (intmask == 0xffffffff)) { 577 return B_UNHANDLED_INTERRUPT; 578 } 579 580 TRACE("interrupt function called %x\n", intmask); 581 582 // handling card presence interrupts 583 if ((intmask & SDHCI_INT_CARD_REM) != 0) { 584 // We can get spurious interrupts as the card is inserted or removed, 585 // so check the actual state before acting 586 if (!fRegisters->present_state.IsCardInserted()) 587 fRegisters->power_control.PowerOff(); 588 else 589 TRACE("Card removed interrupt, but card is inserted\n"); 590 591 fRegisters->interrupt_status |= SDHCI_INT_CARD_REM; 592 TRACE("Card removal interrupt handled\n"); 593 } 594 595 if ((intmask & SDHCI_INT_CARD_INS) != 0) { 596 // We can get spurious interrupts as the card is inserted or removed, 597 // so check the actual state before acting 598 if (fRegisters->present_state.IsCardInserted()) { 599 if (PowerOn()) 600 SetClock(400); 601 release_sem_etc(fScanSemaphore, 1, B_DO_NOT_RESCHEDULE); 602 } else 603 TRACE("Card insertion interrupt, but card is removed\n"); 604 605 fRegisters->interrupt_status |= SDHCI_INT_CARD_INS; 606 TRACE("Card presence interrupt handled\n"); 607 } 608 609 // handling command interrupt 610 if (intmask & SDHCI_INT_CMD_MASK) { 611 fCommandResult = intmask; 612 // Save the status before clearing so the thread can handle it 613 fRegisters->interrupt_status |= (intmask & SDHCI_INT_CMD_MASK); 614 615 // Notify the thread 616 release_sem_etc(fSemaphore, 1, B_DO_NOT_RESCHEDULE); 617 TRACE("Command complete interrupt handled\n"); 618 } 619 620 if (intmask & SDHCI_INT_TRANS_CMP) { 621 fCommandResult = intmask; 622 fRegisters->interrupt_status |= SDHCI_INT_TRANS_CMP; 623 release_sem_etc(fSemaphore, 1, B_DO_NOT_RESCHEDULE); 624 TRACE("Transfer complete interrupt handled\n"); 625 } 626 627 // handling bus power interrupt 628 if (intmask & SDHCI_INT_BUS_POWER) { 629 fRegisters->interrupt_status |= SDHCI_INT_BUS_POWER; 630 TRACE("card is consuming too much power\n"); 631 } 632 633 // Check that all interrupts have been cleared (we check all the ones we 634 // enabled, so that should always be the case) 635 intmask = fRegisters->interrupt_status; 636 if (intmask != 0) { 637 ERROR("Remaining interrupts at end of handler: %x\n", intmask); 638 } 639 640 return B_HANDLED_INTERRUPT; 641 } 642 // #pragma mark - 643 644 645 static status_t 646 init_bus(device_node* node, void** bus_cookie) 647 { 648 CALLED(); 649 650 // Get the PCI driver and device 651 pci_device_module_info* pci; 652 pci_device* device; 653 654 device_node* parent = gDeviceManager->get_parent_node(node); 655 device_node* pciParent = gDeviceManager->get_parent_node(parent); 656 gDeviceManager->get_driver(pciParent, (driver_module_info**)&pci, 657 (void**)&device); 658 gDeviceManager->put_node(pciParent); 659 gDeviceManager->put_node(parent); 660 661 uint8_t bar, slot; 662 if (gDeviceManager->get_attr_uint8(node, SLOT_NUMBER, &slot, false) < B_OK 663 || gDeviceManager->get_attr_uint8(node, BAR_INDEX, &bar, false) < B_OK) 664 return B_BAD_TYPE; 665 666 // Ignore invalid bars 667 TRACE("Register SD bus at slot %d, using bar %d\n", slot + 1, bar); 668 669 pci_info pciInfo; 670 pci->get_pci_info(device, &pciInfo); 671 672 for (; bar < 6 && slot > 0; bar++, slot--) { 673 if ((pciInfo.u.h0.base_register_flags[bar] & PCI_address_type) 674 == PCI_address_type_64) { 675 bar++; 676 } 677 } 678 679 phys_addr_t physicalAddress = pciInfo.u.h0.base_registers[bar]; 680 uint64 barSize = pciInfo.u.h0.base_register_sizes[bar]; 681 if ((pciInfo.u.h0.base_register_flags[bar] & PCI_address_type) 682 == PCI_address_type_64) { 683 physicalAddress |= (uint64)pciInfo.u.h0.base_registers[bar + 1] << 32; 684 barSize |= (uint64)pciInfo.u.h0.base_register_sizes[bar + 1] << 32; 685 } 686 687 if (physicalAddress == 0 || barSize == 0) { 688 ERROR("No registers to map\n"); 689 return B_IO_ERROR; 690 } 691 692 // enable bus master and io 693 uint16 pcicmd = pci->read_pci_config(device, PCI_command, 2); 694 pcicmd &= ~(PCI_command_int_disable | PCI_command_io); 695 pcicmd |= PCI_command_master | PCI_command_memory; 696 pci->write_pci_config(device, PCI_command, 2, pcicmd); 697 698 // map the slot registers 699 area_id regs_area; 700 struct registers* _regs; 701 regs_area = map_physical_memory("sdhc_regs_map", 702 physicalAddress, barSize, B_ANY_KERNEL_BLOCK_ADDRESS, 703 B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, (void**)&_regs); 704 705 if (regs_area < B_OK) { 706 ERROR("Could not map registers\n"); 707 return B_BAD_VALUE; 708 } 709 710 // the interrupt is shared between all busses in an SDHC controller, but 711 // they each register an handler. Not a problem, we will just test the 712 // interrupt registers for all busses one after the other and find no 713 // interrupts on the idle busses. 714 uint8_t irq = pciInfo.u.h0.interrupt_line; 715 TRACE("irq interrupt line: %d\n", irq); 716 717 SdhciBus* bus = new(std::nothrow) SdhciBus(_regs, irq); 718 719 status_t status = B_NO_MEMORY; 720 if (bus != NULL) 721 status = bus->InitCheck(); 722 723 if (status != B_OK) { 724 if (bus != NULL) 725 delete bus; 726 else 727 delete_area(regs_area); 728 return status; 729 } 730 731 // Store the created object as a cookie, allowing users of the bus to 732 // locate it. 733 *bus_cookie = bus; 734 735 return status; 736 } 737 738 739 static void 740 uninit_bus(void* bus_cookie) 741 { 742 SdhciBus* bus = (SdhciBus*)bus_cookie; 743 delete bus; 744 745 // FIXME do we need to put() the PCI module here? 746 } 747 748 749 static void 750 bus_removed(void* bus_cookie) 751 { 752 return; 753 } 754 755 756 static status_t 757 register_child_devices(void* cookie) 758 { 759 CALLED(); 760 SdhciDevice* context = (SdhciDevice*)cookie; 761 device_node* parent = gDeviceManager->get_parent_node(context->fNode); 762 pci_device_module_info* pci; 763 pci_device* device; 764 765 gDeviceManager->get_driver(parent, (driver_module_info**)&pci, 766 (void**)&device); 767 uint8 slotsInfo = pci->read_pci_config(device, SDHCI_PCI_SLOT_INFO, 1); 768 uint8 bar = SDHCI_PCI_SLOT_INFO_FIRST_BASE_INDEX(slotsInfo); 769 uint8 slotsCount = SDHCI_PCI_SLOTS(slotsInfo); 770 771 TRACE("register_child_devices: %u, %u\n", bar, slotsCount); 772 773 char prettyName[25]; 774 775 if (slotsCount > 6 || bar > 5) { 776 ERROR("Invalid slots count: %d or BAR count: %d \n", slotsCount, bar); 777 return B_BAD_VALUE; 778 } 779 780 for (uint8_t slot = 0; slot < slotsCount; slot++) { 781 sprintf(prettyName, "SDHC bus %" B_PRIu8, slot); 782 device_attr attrs[] = { 783 // properties of this controller for mmc bus manager 784 { B_DEVICE_PRETTY_NAME, B_STRING_TYPE, { .string = prettyName } }, 785 { B_DEVICE_FIXED_CHILD, B_STRING_TYPE, 786 {.string = MMC_BUS_MODULE_NAME} }, 787 { B_DEVICE_BUS, B_STRING_TYPE, {.string = "mmc"} }, 788 789 // DMA properties 790 // The high alignment is to force access only to complete sectors 791 // These constraints could be removed by using ADMA which allows 792 // use of the full 64bit address space and can do scatter-gather. 793 { B_DMA_ALIGNMENT, B_UINT32_TYPE, { .ui32 = 511 }}, 794 { B_DMA_HIGH_ADDRESS, B_UINT64_TYPE, { .ui64 = 0x100000000LL }}, 795 { B_DMA_BOUNDARY, B_UINT32_TYPE, { .ui32 = (1 << 19) - 1 }}, 796 { B_DMA_MAX_SEGMENT_COUNT, B_UINT32_TYPE, { .ui32 = 1 }}, 797 { B_DMA_MAX_SEGMENT_BLOCKS, B_UINT32_TYPE, { .ui32 = (1 << 10) - 1 }}, 798 799 // private data to identify device 800 { SLOT_NUMBER, B_UINT8_TYPE, { .ui8 = slot} }, 801 { BAR_INDEX, B_UINT8_TYPE, { .ui8 = bar} }, 802 { NULL } 803 }; 804 device_node* node; 805 if (gDeviceManager->register_node(context->fNode, 806 SDHCI_PCI_MMC_BUS_MODULE_NAME, attrs, NULL, 807 &node) != B_OK) 808 return B_BAD_VALUE; 809 } 810 return B_OK; 811 } 812 813 814 static status_t 815 init_device(device_node* node, void** device_cookie) 816 { 817 CALLED(); 818 819 // Get the PCI driver and device 820 pci_device_module_info* pci; 821 pci_device* device; 822 uint16 vendorId, deviceId; 823 824 device_node* pciParent = gDeviceManager->get_parent_node(node); 825 gDeviceManager->get_driver(pciParent, (driver_module_info**)&pci, 826 (void**)&device); 827 gDeviceManager->put_node(pciParent); 828 829 SdhciDevice* context = new(std::nothrow)SdhciDevice; 830 if (context == NULL) 831 return B_NO_MEMORY; 832 context->fNode = node; 833 *device_cookie = context; 834 835 if (gDeviceManager->get_attr_uint16(node, B_DEVICE_VENDOR_ID, 836 &vendorId, true) != B_OK 837 || gDeviceManager->get_attr_uint16(node, B_DEVICE_ID, &deviceId, 838 true) != B_OK) { 839 panic("No vendor or device id attribute\n"); 840 return B_OK; // Let's hope it didn't need the quirk? 841 } 842 843 if (vendorId == 0x1180 && deviceId == 0xe823) { 844 // Switch the device to SD2.0 mode 845 // This should change its device id to 0xe822 if succesful. 846 // The device then remains in SD2.0 mode even after reboot. 847 pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0xfc); 848 context->fRicohOriginalMode = pci->read_pci_config(device, 849 SDHCI_PCI_RICOH_MODE, 1); 850 pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE, 1, 851 SDHCI_PCI_RICOH_MODE_SD20); 852 pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0); 853 854 deviceId = pci->read_pci_config(device, 2, 2); 855 TRACE("Device ID after Ricoh quirk: %x\n", deviceId); 856 } 857 858 return B_OK; 859 } 860 861 862 static void 863 uninit_device(void* device_cookie) 864 { 865 // Get the PCI driver and device 866 pci_device_module_info* pci; 867 pci_device* device; 868 uint16 vendorId, deviceId; 869 870 SdhciDevice* context = (SdhciDevice*)device_cookie; 871 device_node* pciParent = gDeviceManager->get_parent_node(context->fNode); 872 gDeviceManager->get_driver(pciParent, (driver_module_info**)&pci, 873 (void**)&device); 874 875 if (gDeviceManager->get_attr_uint16(context->fNode, B_DEVICE_VENDOR_ID, 876 &vendorId, true) != B_OK 877 || gDeviceManager->get_attr_uint16(context->fNode, B_DEVICE_ID, 878 &deviceId, false) != B_OK) { 879 ERROR("No vendor or device id attribute\n"); 880 } else if (vendorId == 0x1180 && deviceId == 0xe823) { 881 pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0xfc); 882 pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE, 1, 883 context->fRicohOriginalMode); 884 pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0); 885 } 886 887 gDeviceManager->put_node(pciParent); 888 889 delete context; 890 } 891 892 893 static status_t 894 register_device(device_node* parent) 895 { 896 device_attr attrs[] = { 897 {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {.string = "SD Host Controller"}}, 898 {} 899 }; 900 901 return gDeviceManager->register_node(parent, SDHCI_PCI_DEVICE_MODULE_NAME, 902 attrs, NULL, NULL); 903 } 904 905 906 static float 907 supports_device(device_node* parent) 908 { 909 const char* bus; 910 uint16 type, subType; 911 uint16 vendorId, deviceId; 912 913 // make sure parent is a PCI SDHCI device node 914 if (gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false) 915 != B_OK) { 916 TRACE("Could not find required attribute device/bus\n"); 917 return -1; 918 } 919 920 if (strcmp(bus, "pci") != 0) 921 return 0.0f; 922 923 if (gDeviceManager->get_attr_uint16(parent, B_DEVICE_VENDOR_ID, &vendorId, 924 false) != B_OK 925 || gDeviceManager->get_attr_uint16(parent, B_DEVICE_ID, &deviceId, 926 false) != B_OK) { 927 TRACE("No vendor or device id attribute\n"); 928 return 0.0f; 929 } 930 931 TRACE("supports_device(vid:%04x pid:%04x)\n", vendorId, deviceId); 932 933 if (gDeviceManager->get_attr_uint16(parent, B_DEVICE_SUB_TYPE, &subType, 934 false) < B_OK 935 || gDeviceManager->get_attr_uint16(parent, B_DEVICE_TYPE, &type, 936 false) < B_OK) { 937 TRACE("Could not find type/subtype attributes\n"); 938 return -1; 939 } 940 941 if (type == PCI_base_peripheral) { 942 if (subType != PCI_sd_host) { 943 // Also accept some compliant devices that do not advertise 944 // themselves as such. 945 if (vendorId != 0x1180 946 || (deviceId != 0xe823 && deviceId != 0xe822)) { 947 TRACE("Not the right subclass, and not a Ricoh device\n"); 948 return 0.0f; 949 } 950 } 951 952 pci_device_module_info* pci; 953 pci_device* device; 954 gDeviceManager->get_driver(parent, (driver_module_info**)&pci, 955 (void**)&device); 956 TRACE("SDHCI Device found! Subtype: 0x%04x, type: 0x%04x\n", 957 subType, type); 958 959 return 0.8f; 960 } 961 962 return 0.0f; 963 } 964 965 966 static status_t 967 set_clock(void* controller, uint32_t kilohertz) 968 { 969 SdhciBus* bus = (SdhciBus*)controller; 970 bus->SetClock(kilohertz); 971 return B_OK; 972 } 973 974 975 static status_t 976 execute_command(void* controller, uint8_t command, uint32_t argument, 977 uint32_t* response) 978 { 979 SdhciBus* bus = (SdhciBus*)controller; 980 return bus->ExecuteCommand(command, argument, response); 981 } 982 983 984 static status_t 985 do_io(void* controller, uint8_t command, IOOperation* operation, 986 bool offsetAsSectors) 987 { 988 CALLED(); 989 990 SdhciBus* bus = (SdhciBus*)controller; 991 return bus->DoIO(command, operation, offsetAsSectors); 992 } 993 994 995 static void 996 set_scan_semaphore(void* controller, sem_id sem) 997 { 998 CALLED(); 999 1000 SdhciBus* bus = (SdhciBus*)controller; 1001 return bus->SetScanSemaphore(sem); 1002 } 1003 1004 1005 static void 1006 set_bus_width(void* controller, int width) 1007 { 1008 CALLED(); 1009 1010 SdhciBus* bus = (SdhciBus*)controller; 1011 return bus->SetBusWidth(width); 1012 } 1013 1014 1015 module_dependency module_dependencies[] = { 1016 { MMC_BUS_MODULE_NAME, (module_info**)&gMMCBusController}, 1017 { B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&gDeviceManager }, 1018 {} 1019 }; 1020 1021 1022 // Device node registered for each SD slot. It implements the MMC operations so 1023 // the bus manager can use it to communicate with SD cards. 1024 static mmc_bus_interface gSDHCIPCIDeviceModule = { 1025 { 1026 { 1027 SDHCI_PCI_MMC_BUS_MODULE_NAME, 1028 0, 1029 NULL 1030 }, 1031 NULL, // supports device 1032 NULL, // register device 1033 init_bus, 1034 uninit_bus, 1035 NULL, // register child devices 1036 NULL, // rescan 1037 bus_removed, 1038 }, 1039 1040 set_clock, 1041 execute_command, 1042 do_io, 1043 set_scan_semaphore, 1044 set_bus_width 1045 }; 1046 1047 1048 // Root device that binds to the PCI bus. It will register an mmc_bus_interface 1049 // node for each SD slot in the device. 1050 static driver_module_info sSDHCIDevice = { 1051 { 1052 SDHCI_PCI_DEVICE_MODULE_NAME, 1053 0, 1054 NULL 1055 }, 1056 supports_device, 1057 register_device, 1058 init_device, 1059 uninit_device, 1060 register_child_devices, 1061 NULL, // rescan 1062 NULL, // device removed 1063 }; 1064 1065 1066 module_info* modules[] = { 1067 (module_info* )&sSDHCIDevice, 1068 (module_info* )&gSDHCIPCIDeviceModule, 1069 NULL 1070 }; 1071