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