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