xref: /haiku/src/add-ons/kernel/busses/mmc/sdhci_pci.cpp (revision acdafb571df692fab7ad89836e39590dd8d415e2)
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 SLOTS_COUNT				"device/slots_count"
39 #define SLOT_NUMBER				"device/slot"
40 #define BAR_INDEX				"device/bar"
41 
42 
43 class SdhciBus {
44 	public:
45 							SdhciBus(struct registers* registers, uint8_t irq);
46 							~SdhciBus();
47 
48 		void				EnableInterrupts(uint32_t mask);
49 		void				DisableInterrupts();
50 		status_t			ExecuteCommand(uint8_t command, uint32_t argument,
51 								uint32_t* response);
52 		int32				HandleInterrupt();
53 		status_t			InitCheck();
54 		void				Reset();
55 		void				SetClock(int kilohertz);
56 		status_t			DoIO(uint8_t command, IOOperation* operation,
57 								bool offsetAsSectors);
58 		void				SetScanSemaphore(sem_id sem);
59 		void				SetBusWidth(int width);
60 
61 	private:
62 		bool				PowerOn();
63 		void				RecoverError();
64 
65 	private:
66 		struct registers*	fRegisters;
67 		uint32_t			fCommandResult;
68 		uint8_t				fIrq;
69 		sem_id				fSemaphore;
70 		sem_id				fScanSemaphore;
71 		status_t			fStatus;
72 };
73 
74 
75 class SdhciDevice {
76 	public:
77 		device_node* fNode;
78 		uint8_t fRicohOriginalMode;
79 };
80 
81 
82 device_manager_info* gDeviceManager;
83 device_module_info* gMMCBusController;
84 static pci_x86_module_info* sPCIx86Module;
85 
86 
87 static int32
88 sdhci_generic_interrupt(void* data)
89 {
90 	SdhciBus* bus = (SdhciBus*)data;
91 	return bus->HandleInterrupt();
92 }
93 
94 
95 SdhciBus::SdhciBus(struct registers* registers, uint8_t irq)
96 	:
97 	fRegisters(registers),
98 	fIrq(irq),
99 	fSemaphore(0)
100 {
101 	if (irq == 0 || irq == 0xff) {
102 		ERROR("PCI IRQ not assigned\n");
103 		fStatus = B_BAD_DATA;
104 		return;
105 	}
106 
107 	fSemaphore = create_sem(0, "SDHCI interrupts");
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 	while (fRegisters->present_state.CommandInhibit()
263 		&& (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 	fRegisters->software_reset.ResetAll();
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 	if (get_module(B_PCI_X86_MODULE_NAME, (module_info**)&sPCIx86Module)
662 	    != B_OK) {
663 	    sPCIx86Module = NULL;
664 		ERROR("PCIx86Module not loaded\n");
665 		// FIXME try probing FDT as well
666 		return -1;
667 	}
668 
669 	uint8_t bar, slot;
670 	if (gDeviceManager->get_attr_uint8(node, SLOT_NUMBER, &slot, false) < B_OK
671 		|| gDeviceManager->get_attr_uint8(node, BAR_INDEX, &bar, false) < B_OK)
672 		return -1;
673 
674 	// Ignore invalid bars
675 	TRACE("Register SD bus at slot %d, using bar %d\n", slot + 1, bar);
676 
677 	pci_info pciInfo;
678 	pci->get_pci_info(device, &pciInfo);
679 
680 	if (pciInfo.u.h0.base_register_sizes[bar] == 0) {
681 		ERROR("No registers to map\n");
682 		return -1;
683 	}
684 
685 	int msiCount = sPCIx86Module->get_msi_count(pciInfo.bus,
686 		pciInfo.device, pciInfo.function);
687 	TRACE("interrupts count: %d\n",msiCount);
688 	// FIXME if available, use MSI rather than good old IRQ...
689 
690 	// enable bus master and io
691 	uint16 pcicmd = pci->read_pci_config(device, PCI_command, 2);
692 	pcicmd &= ~(PCI_command_int_disable | PCI_command_io);
693 	pcicmd |= PCI_command_master | PCI_command_memory;
694 	pci->write_pci_config(device, PCI_command, 2, pcicmd);
695 
696 	// map the slot registers
697 	area_id	regs_area;
698 	struct registers* _regs;
699 	regs_area = map_physical_memory("sdhc_regs_map",
700 		pciInfo.u.h0.base_registers[bar],
701 		pciInfo.u.h0.base_register_sizes[bar], B_ANY_KERNEL_BLOCK_ADDRESS,
702 		B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, (void**)&_regs);
703 
704 	if (regs_area < B_OK) {
705 		ERROR("Could not map registers\n");
706 		return B_BAD_VALUE;
707 	}
708 
709 	// the interrupt is shared between all busses in an SDHC controller, but
710 	// they each register an handler. Not a problem, we will just test the
711 	// interrupt registers for all busses one after the other and find no
712 	// interrupts on the idle busses.
713 	uint8_t irq = pciInfo.u.h0.interrupt_line;
714 	TRACE("irq interrupt line: %d\n", irq);
715 
716 	SdhciBus* bus = new(std::nothrow) SdhciBus(_regs, irq);
717 
718 	status_t status = B_NO_MEMORY;
719 	if (bus != NULL)
720 		status = bus->InitCheck();
721 
722 	if (status != B_OK) {
723 		if (sPCIx86Module != NULL) {
724 			put_module(B_PCI_X86_MODULE_NAME);
725 			sPCIx86Module = NULL;
726 		}
727 
728 		if (bus != NULL)
729 			delete bus;
730 		else
731 			delete_area(regs_area);
732 		return status;
733 	}
734 
735 	// Store the created object as a cookie, allowing users of the bus to
736 	// locate it.
737 	*bus_cookie = bus;
738 
739 	return status;
740 }
741 
742 
743 static void
744 uninit_bus(void* bus_cookie)
745 {
746 	SdhciBus* bus = (SdhciBus*)bus_cookie;
747 	delete bus;
748 
749 	// FIXME do we need to put() the PCI module here?
750 }
751 
752 
753 static void
754 bus_removed(void* bus_cookie)
755 {
756 	return;
757 }
758 
759 
760 static status_t
761 register_child_devices(void* cookie)
762 {
763 	CALLED();
764 	SdhciDevice* context = (SdhciDevice*)cookie;
765 	device_node* parent = gDeviceManager->get_parent_node(context->fNode);
766 	pci_device_module_info* pci;
767 	pci_device* device;
768 	uint8 slots_count, bar, slotsInfo;
769 
770 	gDeviceManager->get_driver(parent, (driver_module_info**)&pci,
771 		(void**)&device);
772 	slotsInfo = pci->read_pci_config(device, SDHCI_PCI_SLOT_INFO, 1);
773 	bar = SDHCI_PCI_SLOT_INFO_FIRST_BASE_INDEX(slotsInfo);
774 	slots_count = SDHCI_PCI_SLOTS(slotsInfo);
775 
776 	char prettyName[25];
777 
778 	if (slots_count > 6 || bar > 5) {
779 		ERROR("Invalid slots count: %d or BAR count: %d \n", slots_count, bar);
780 		return B_BAD_VALUE;
781 	}
782 
783 	for (uint8_t slot = 0; slot <= slots_count; slot++) {
784 
785 		bar = bar + slot;
786 		sprintf(prettyName, "SDHC bus %" B_PRIu8, slot);
787 		device_attr attrs[] = {
788 			// properties of this controller for mmc bus manager
789 			{ B_DEVICE_PRETTY_NAME, B_STRING_TYPE, { string: prettyName } },
790 			{ B_DEVICE_FIXED_CHILD, B_STRING_TYPE,
791 				{string: MMC_BUS_MODULE_NAME} },
792 			{ B_DEVICE_BUS, B_STRING_TYPE, {string: "mmc"} },
793 
794 			// DMA properties
795 			// The high alignment is to force access only to complete sectors
796 			// These constraints could be removed by using ADMA which allows
797 			// use of the full 64bit address space and can do scatter-gather.
798 			{ B_DMA_ALIGNMENT, B_UINT32_TYPE, { ui32: 511 }},
799 			{ B_DMA_HIGH_ADDRESS, B_UINT64_TYPE, { ui64: 0x100000000LL }},
800 			{ B_DMA_BOUNDARY, B_UINT32_TYPE, { ui32: (1 << 19) - 1 }},
801 			{ B_DMA_MAX_SEGMENT_COUNT, B_UINT32_TYPE, { ui32: 1 }},
802 			{ B_DMA_MAX_SEGMENT_BLOCKS, B_UINT32_TYPE, { ui32: (1 << 10) - 1 }},
803 
804 			// private data to identify device
805 			{ SLOT_NUMBER, B_UINT8_TYPE, { ui8: slot} },
806 			{ BAR_INDEX, B_UINT8_TYPE, { ui8: bar} },
807 			{ NULL }
808 		};
809 		device_node* node;
810 		if (gDeviceManager->register_node(context->fNode,
811 				SDHCI_PCI_MMC_BUS_MODULE_NAME, attrs, NULL,
812 				&node) != B_OK)
813 			return B_BAD_VALUE;
814 	}
815 	return B_OK;
816 }
817 
818 
819 static status_t
820 init_device(device_node* node, void** device_cookie)
821 {
822 	CALLED();
823 
824 	// Get the PCI driver and device
825 	pci_device_module_info* pci;
826 	pci_device* device;
827 	uint16 vendorId, deviceId;
828 
829 	device_node* pciParent = gDeviceManager->get_parent_node(node);
830 	gDeviceManager->get_driver(pciParent, (driver_module_info**)&pci,
831 	        (void**)&device);
832 	gDeviceManager->put_node(pciParent);
833 
834 	SdhciDevice* context = new(std::nothrow)SdhciDevice;
835 	if (context == NULL)
836 		return B_NO_MEMORY;
837 	context->fNode = node;
838 	*device_cookie = context;
839 
840 	if (gDeviceManager->get_attr_uint16(node, B_DEVICE_VENDOR_ID,
841 			&vendorId, true) != B_OK
842 		|| gDeviceManager->get_attr_uint16(node, B_DEVICE_ID, &deviceId,
843 			true) != B_OK) {
844 		panic("No vendor or device id attribute\n");
845 		return B_OK; // Let's hope it didn't need the quirk?
846 	}
847 
848 	if (vendorId == 0x1180 && deviceId == 0xe823) {
849 		// Switch the device to SD2.0 mode
850 		// This should change its device id to 0xe822 if succesful.
851 		// The device then remains in SD2.0 mode even after reboot.
852 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0xfc);
853 		context->fRicohOriginalMode = pci->read_pci_config(device,
854 			SDHCI_PCI_RICOH_MODE, 1);
855 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE, 1,
856 			SDHCI_PCI_RICOH_MODE_SD20);
857 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0);
858 
859 		deviceId = pci->read_pci_config(device, 2, 2);
860 		TRACE("Device ID after Ricoh quirk: %x\n", deviceId);
861 	}
862 
863 	return B_OK;
864 }
865 
866 
867 static void
868 uninit_device(void* device_cookie)
869 {
870 	// Get the PCI driver and device
871 	pci_device_module_info* pci;
872 	pci_device* device;
873 	uint16 vendorId, deviceId;
874 
875 	SdhciDevice* context = (SdhciDevice*)device_cookie;
876 	device_node* pciParent = gDeviceManager->get_parent_node(context->fNode);
877 	gDeviceManager->get_driver(pciParent, (driver_module_info**)&pci,
878 	        (void**)&device);
879 
880 	if (gDeviceManager->get_attr_uint16(context->fNode, B_DEVICE_VENDOR_ID,
881 			&vendorId, true) != B_OK
882 		|| gDeviceManager->get_attr_uint16(context->fNode, B_DEVICE_ID,
883 			&deviceId, false) != B_OK) {
884 		ERROR("No vendor or device id attribute\n");
885 	} else if (vendorId == 0x1180 && deviceId == 0xe823) {
886 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0xfc);
887 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE, 1,
888 			context->fRicohOriginalMode);
889 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0);
890 	}
891 
892 	gDeviceManager->put_node(pciParent);
893 
894 	delete context;
895 }
896 
897 
898 static status_t
899 register_device(device_node* parent)
900 {
901 	device_attr attrs[] = {
902 		{B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "SD Host Controller"}},
903 		{}
904 	};
905 
906 	return gDeviceManager->register_node(parent, SDHCI_PCI_DEVICE_MODULE_NAME,
907 		attrs, NULL, NULL);
908 }
909 
910 
911 static float
912 supports_device(device_node* parent)
913 {
914 	const char* bus;
915 	uint16 type, subType;
916 	uint16 vendorId, deviceId;
917 
918 	// make sure parent is a PCI SDHCI device node
919 	if (gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false)
920 		!= B_OK) {
921 		TRACE("Could not find required attribute device/bus\n");
922 		return -1;
923 	}
924 
925 	if (strcmp(bus, "pci") != 0)
926 		return 0.0f;
927 
928 	if (gDeviceManager->get_attr_uint16(parent, B_DEVICE_VENDOR_ID, &vendorId,
929 			false) != B_OK
930 		|| gDeviceManager->get_attr_uint16(parent, B_DEVICE_ID, &deviceId,
931 			false) != B_OK) {
932 		TRACE("No vendor or device id attribute\n");
933 		return 0.0f;
934 	}
935 
936 	TRACE("supports_device(vid:%04x pid:%04x)\n", vendorId, deviceId);
937 
938 	if (gDeviceManager->get_attr_uint16(parent, B_DEVICE_SUB_TYPE, &subType,
939 			false) < B_OK
940 		|| gDeviceManager->get_attr_uint16(parent, B_DEVICE_TYPE, &type,
941 			false) < B_OK) {
942 		TRACE("Could not find type/subtype attributes\n");
943 		return -1;
944 	}
945 
946 	if (type == PCI_base_peripheral) {
947 		if (subType != PCI_sd_host) {
948 			// Also accept some compliant devices that do not advertise
949 			// themselves as such.
950 			if (vendorId != 0x1180
951 				|| (deviceId != 0xe823 && deviceId != 0xe822)) {
952 				TRACE("Not the right subclass, and not a Ricoh device\n");
953 				return 0.0f;
954 			}
955 		}
956 
957 		pci_device_module_info* pci;
958 		pci_device* device;
959 		gDeviceManager->get_driver(parent, (driver_module_info**)&pci,
960 			(void**)&device);
961 		TRACE("SDHCI Device found! Subtype: 0x%04x, type: 0x%04x\n",
962 			subType, type);
963 
964 		return 0.8f;
965 	}
966 
967 	return 0.0f;
968 }
969 
970 
971 static status_t
972 set_clock(void* controller, uint32_t kilohertz)
973 {
974 	SdhciBus* bus = (SdhciBus*)controller;
975 	bus->SetClock(kilohertz);
976 	return B_OK;
977 }
978 
979 
980 static status_t
981 execute_command(void* controller, uint8_t command, uint32_t argument,
982 	uint32_t* response)
983 {
984 	SdhciBus* bus = (SdhciBus*)controller;
985 	return bus->ExecuteCommand(command, argument, response);
986 }
987 
988 
989 static status_t
990 do_io(void* controller, uint8_t command, IOOperation* operation,
991 	bool offsetAsSectors)
992 {
993 	CALLED();
994 
995 	SdhciBus* bus = (SdhciBus*)controller;
996 	return bus->DoIO(command, operation, offsetAsSectors);
997 }
998 
999 
1000 static void
1001 set_scan_semaphore(void* controller, sem_id sem)
1002 {
1003 	CALLED();
1004 
1005 	SdhciBus* bus = (SdhciBus*)controller;
1006 	return bus->SetScanSemaphore(sem);
1007 }
1008 
1009 
1010 static void
1011 set_bus_width(void* controller, int width)
1012 {
1013 	CALLED();
1014 
1015 	SdhciBus* bus = (SdhciBus*)controller;
1016 	return bus->SetBusWidth(width);
1017 }
1018 
1019 
1020 module_dependency module_dependencies[] = {
1021 	{ MMC_BUS_MODULE_NAME, (module_info**)&gMMCBusController},
1022 	{ B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&gDeviceManager },
1023 	{}
1024 };
1025 
1026 
1027 // Device node registered for each SD slot. It implements the MMC operations so
1028 // the bus manager can use it to communicate with SD cards.
1029 static mmc_bus_interface gSDHCIPCIDeviceModule = {
1030 	{
1031 		{
1032 			SDHCI_PCI_MMC_BUS_MODULE_NAME,
1033 			0,
1034 			NULL
1035 		},
1036 		NULL,	// supports device
1037 		NULL,	// register device
1038 		init_bus,
1039 		uninit_bus,
1040 		NULL,	// register child devices
1041 		NULL,	// rescan
1042 		bus_removed,
1043 	},
1044 
1045 	set_clock,
1046 	execute_command,
1047 	do_io,
1048 	set_scan_semaphore,
1049 	set_bus_width
1050 };
1051 
1052 
1053 // Root device that binds to the PCI bus. It will register an mmc_bus_interface
1054 // node for each SD slot in the device.
1055 static driver_module_info sSDHCIDevice = {
1056 	{
1057 		SDHCI_PCI_DEVICE_MODULE_NAME,
1058 		0,
1059 		NULL
1060 	},
1061 	supports_device,
1062 	register_device,
1063 	init_device,
1064 	uninit_device,
1065 	register_child_devices,
1066 	NULL,	// rescan
1067 	NULL,	// device removed
1068 };
1069 
1070 
1071 module_info* modules[] = {
1072 	(module_info* )&sSDHCIDevice,
1073 	(module_info* )&gSDHCIPCIDeviceModule,
1074 	NULL
1075 };
1076