xref: /haiku/src/add-ons/kernel/busses/mmc/sdhci_pci.cpp (revision 445d4fd926c569e7b9ae28017da86280aaecbae2)
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 
16 #include <KernelExport.h>
17 
18 #include "IOSchedulerSimple.h"
19 #include "mmc.h"
20 #include "sdhci_pci.h"
21 
22 
23 #define TRACE_SDHCI
24 #ifdef TRACE_SDHCI
25 #	define TRACE(x...) dprintf("\33[33msdhci_pci:\33[0m " x)
26 #else
27 #	define TRACE(x...) ;
28 #endif
29 #define TRACE_ALWAYS(x...)	dprintf("\33[33msdhci_pci:\33[0m " x)
30 #define ERROR(x...)			dprintf("\33[33msdhci_pci:\33[0m " x)
31 #define CALLED(x...)		TRACE("CALLED %s\n", __PRETTY_FUNCTION__)
32 
33 
34 #define SDHCI_PCI_DEVICE_MODULE_NAME "busses/mmc/sdhci_pci/driver_v1"
35 #define SDHCI_PCI_MMC_BUS_MODULE_NAME "busses/mmc/sdhci_pci/device/v1"
36 
37 #define SLOT_NUMBER				"device/slot"
38 #define BAR_INDEX				"device/bar"
39 
40 
41 class SdhciBus {
42 	public:
43 							SdhciBus(struct registers* registers, uint8_t irq);
44 							~SdhciBus();
45 
46 		void				EnableInterrupts(uint32_t mask);
47 		void				DisableInterrupts();
48 		status_t			ExecuteCommand(uint8_t command, uint32_t argument,
49 								uint32_t* response);
50 		int32				HandleInterrupt();
51 		status_t			InitCheck();
52 		void				Reset();
53 		void				SetClock(int kilohertz);
54 		status_t			DoIO(uint8_t command, IOOperation* operation,
55 								bool offsetAsSectors);
56 		void				SetScanSemaphore(sem_id sem);
57 		void				SetBusWidth(int width);
58 
59 	private:
60 		bool				PowerOn();
61 		void				RecoverError();
62 
63 	private:
64 		struct registers*	fRegisters;
65 		uint32_t			fCommandResult;
66 		uint8_t				fIrq;
67 		sem_id				fSemaphore;
68 		sem_id				fScanSemaphore;
69 		status_t			fStatus;
70 };
71 
72 
73 class SdhciDevice {
74 	public:
75 		device_node* fNode;
76 		uint8_t fRicohOriginalMode;
77 };
78 
79 
80 device_manager_info* gDeviceManager;
81 device_module_info* gMMCBusController;
82 
83 
84 static int32
85 sdhci_generic_interrupt(void* data)
86 {
87 	SdhciBus* bus = (SdhciBus*)data;
88 	return bus->HandleInterrupt();
89 }
90 
91 
92 SdhciBus::SdhciBus(struct registers* registers, uint8_t irq)
93 	:
94 	fRegisters(registers),
95 	fIrq(irq),
96 	fSemaphore(0)
97 {
98 	if (irq == 0 || irq == 0xff) {
99 		ERROR("PCI IRQ not assigned\n");
100 		fStatus = B_BAD_DATA;
101 		return;
102 	}
103 
104 	fSemaphore = create_sem(0, "SDHCI interrupts");
105 
106 	DisableInterrupts();
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 	do {
262 		acquire_sem(fSemaphore);
263 		TRACE("command complete sem acquired, status: %x\n", fCommandResult);
264 		TRACE("real status = %x command line busy: %d\n",
265 			fRegisters->interrupt_status,
266 			fRegisters->present_state.CommandInhibit());
267 	} while (fCommandResult == 0);
268 
269 	TRACE("Command response available\n");
270 
271 	if (fCommandResult & SDHCI_INT_ERROR) {
272 		fRegisters->interrupt_status |= fCommandResult;
273 		if (fCommandResult & SDHCI_INT_TIMEOUT) {
274 			ERROR("Command execution timed out\n");
275 			if (fRegisters->present_state.CommandInhibit()) {
276 				TRACE("Command line is still busy, clearing it\n");
277 				// Clear the stall
278 				fRegisters->software_reset.ResetCommandLine();
279 			}
280 			return B_TIMED_OUT;
281 		}
282 		if (fCommandResult & SDHCI_INT_CRC) {
283 			ERROR("CRC error\n");
284 			return B_BAD_VALUE;
285 		}
286 		ERROR("Command execution failed %x\n", fCommandResult);
287 		// TODO look at errors in interrupt_status register for more details
288 		// and return a more appropriate error code
289 		return B_ERROR;
290 	}
291 
292 	if (fRegisters->present_state.CommandInhibit()) {
293 		TRACE("Command execution failed, card stalled\n");
294 		// Clear the stall
295 		fRegisters->software_reset.ResetCommandLine();
296 		return B_ERROR;
297 	}
298 
299 	switch (replyType & Command::kReplySizeMask) {
300 		case Command::k32BitResponse:
301 			*response = fRegisters->response[0];
302 			break;
303 		case Command::k128BitResponse:
304 			response[0] = fRegisters->response[0];
305 			response[1] = fRegisters->response[1];
306 			response[2] = fRegisters->response[2];
307 			response[3] = fRegisters->response[3];
308 			break;
309 
310 		default:
311 			// No response
312 			break;
313 	}
314 
315 	if (replyType == Command::kR1bType
316 			&& (fCommandResult & SDHCI_INT_TRANS_CMP) == 0) {
317 		// R1b commands may use the data line so we must wait for the
318 		// "transfer complete" interrupt here.
319 		TRACE("Waiting for data line...\n");
320 		do {
321 			acquire_sem(fSemaphore);
322 		} while (fRegisters->present_state.DataInhibit());
323 		TRACE("Dataline is released.\n");
324 	}
325 
326 	ERROR("Command execution %d complete\n", command);
327 	return B_OK;
328 }
329 
330 
331 status_t
332 SdhciBus::InitCheck()
333 {
334 	return fStatus;
335 }
336 
337 
338 void
339 SdhciBus::Reset()
340 {
341 	if (!fRegisters->software_reset.ResetAll())
342 		ERROR("SdhciBus::Reset: SoftwareReset timeout\n");
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 	uint8_t bar, slot;
661 	if (gDeviceManager->get_attr_uint8(node, SLOT_NUMBER, &slot, false) < B_OK
662 		|| gDeviceManager->get_attr_uint8(node, BAR_INDEX, &bar, false) < B_OK)
663 		return B_BAD_TYPE;
664 
665 	// Ignore invalid bars
666 	TRACE("Register SD bus at slot %d, using bar %d\n", slot + 1, bar);
667 
668 	pci_info pciInfo;
669 	pci->get_pci_info(device, &pciInfo);
670 
671 	for (; bar < 6 && slot > 0; bar++, slot--) {
672 		if ((pciInfo.u.h0.base_register_flags[bar] & PCI_address_type)
673 			== PCI_address_type_64) {
674 			bar++;
675 		}
676 	}
677 
678 	phys_addr_t physicalAddress = pciInfo.u.h0.base_registers[bar];
679 	uint64 barSize = pciInfo.u.h0.base_register_sizes[bar];
680 	if ((pciInfo.u.h0.base_register_flags[bar] & PCI_address_type)
681 			== PCI_address_type_64) {
682 		physicalAddress |= (uint64)pciInfo.u.h0.base_registers[bar + 1] << 32;
683 		barSize |= (uint64)pciInfo.u.h0.base_register_sizes[bar + 1] << 32;
684 	}
685 
686 	if (physicalAddress == 0 || barSize == 0) {
687 		ERROR("No registers to map\n");
688 		return B_IO_ERROR;
689 	}
690 
691 	// enable bus master and io
692 	uint16 pcicmd = pci->read_pci_config(device, PCI_command, 2);
693 	pcicmd &= ~(PCI_command_int_disable | PCI_command_io);
694 	pcicmd |= PCI_command_master | PCI_command_memory;
695 	pci->write_pci_config(device, PCI_command, 2, pcicmd);
696 
697 	// map the slot registers
698 	area_id	regs_area;
699 	struct registers* _regs;
700 	regs_area = map_physical_memory("sdhc_regs_map",
701 		physicalAddress, barSize, 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 (bus != NULL)
724 			delete bus;
725 		else
726 			delete_area(regs_area);
727 		return status;
728 	}
729 
730 	// Store the created object as a cookie, allowing users of the bus to
731 	// locate it.
732 	*bus_cookie = bus;
733 
734 	return status;
735 }
736 
737 
738 static void
739 uninit_bus(void* bus_cookie)
740 {
741 	SdhciBus* bus = (SdhciBus*)bus_cookie;
742 	delete bus;
743 
744 	// FIXME do we need to put() the PCI module here?
745 }
746 
747 
748 static void
749 bus_removed(void* bus_cookie)
750 {
751 	return;
752 }
753 
754 
755 static status_t
756 register_child_devices(void* cookie)
757 {
758 	CALLED();
759 	SdhciDevice* context = (SdhciDevice*)cookie;
760 	device_node* parent = gDeviceManager->get_parent_node(context->fNode);
761 	pci_device_module_info* pci;
762 	pci_device* device;
763 
764 	gDeviceManager->get_driver(parent, (driver_module_info**)&pci,
765 		(void**)&device);
766 	uint8 slotsInfo = pci->read_pci_config(device, SDHCI_PCI_SLOT_INFO, 1);
767 	uint8 bar = SDHCI_PCI_SLOT_INFO_FIRST_BASE_INDEX(slotsInfo);
768 	uint8 slotsCount = SDHCI_PCI_SLOTS(slotsInfo);
769 
770 	TRACE("register_child_devices: %u, %u\n", bar, slotsCount);
771 
772 	char prettyName[25];
773 
774 	if (slotsCount > 6 || bar > 5) {
775 		ERROR("Invalid slots count: %d or BAR count: %d \n", slotsCount, bar);
776 		return B_BAD_VALUE;
777 	}
778 
779 	for (uint8_t slot = 0; slot < slotsCount; slot++) {
780 		sprintf(prettyName, "SDHC bus %" B_PRIu8, slot);
781 		device_attr attrs[] = {
782 			// properties of this controller for mmc bus manager
783 			{ B_DEVICE_PRETTY_NAME, B_STRING_TYPE, { .string = prettyName } },
784 			{ B_DEVICE_FIXED_CHILD, B_STRING_TYPE,
785 				{.string = MMC_BUS_MODULE_NAME} },
786 			{ B_DEVICE_BUS, B_STRING_TYPE, {.string = "mmc"} },
787 
788 			// DMA properties
789 			// The high alignment is to force access only to complete sectors
790 			// These constraints could be removed by using ADMA which allows
791 			// use of the full 64bit address space and can do scatter-gather.
792 			{ B_DMA_ALIGNMENT, B_UINT32_TYPE, { .ui32 = 511 }},
793 			{ B_DMA_HIGH_ADDRESS, B_UINT64_TYPE, { .ui64 = 0x100000000LL }},
794 			{ B_DMA_BOUNDARY, B_UINT32_TYPE, { .ui32 = (1 << 19) - 1 }},
795 			{ B_DMA_MAX_SEGMENT_COUNT, B_UINT32_TYPE, { .ui32 = 1 }},
796 			{ B_DMA_MAX_SEGMENT_BLOCKS, B_UINT32_TYPE, { .ui32 = (1 << 10) - 1 }},
797 
798 			// private data to identify device
799 			{ SLOT_NUMBER, B_UINT8_TYPE, { .ui8 = slot} },
800 			{ BAR_INDEX, B_UINT8_TYPE, { .ui8 = bar} },
801 			{ NULL }
802 		};
803 		device_node* node;
804 		if (gDeviceManager->register_node(context->fNode,
805 				SDHCI_PCI_MMC_BUS_MODULE_NAME, attrs, NULL,
806 				&node) != B_OK)
807 			return B_BAD_VALUE;
808 	}
809 	return B_OK;
810 }
811 
812 
813 static status_t
814 init_device(device_node* node, void** device_cookie)
815 {
816 	CALLED();
817 
818 	// Get the PCI driver and device
819 	pci_device_module_info* pci;
820 	pci_device* device;
821 	uint16 vendorId, deviceId;
822 
823 	device_node* pciParent = gDeviceManager->get_parent_node(node);
824 	gDeviceManager->get_driver(pciParent, (driver_module_info**)&pci,
825 	        (void**)&device);
826 	gDeviceManager->put_node(pciParent);
827 
828 	SdhciDevice* context = new(std::nothrow)SdhciDevice;
829 	if (context == NULL)
830 		return B_NO_MEMORY;
831 	context->fNode = node;
832 	*device_cookie = context;
833 
834 	if (gDeviceManager->get_attr_uint16(node, B_DEVICE_VENDOR_ID,
835 			&vendorId, true) != B_OK
836 		|| gDeviceManager->get_attr_uint16(node, B_DEVICE_ID, &deviceId,
837 			true) != B_OK) {
838 		panic("No vendor or device id attribute\n");
839 		return B_OK; // Let's hope it didn't need the quirk?
840 	}
841 
842 	if (vendorId == 0x1180 && deviceId == 0xe823) {
843 		// Switch the device to SD2.0 mode
844 		// This should change its device id to 0xe822 if succesful.
845 		// The device then remains in SD2.0 mode even after reboot.
846 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0xfc);
847 		context->fRicohOriginalMode = pci->read_pci_config(device,
848 			SDHCI_PCI_RICOH_MODE, 1);
849 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE, 1,
850 			SDHCI_PCI_RICOH_MODE_SD20);
851 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0);
852 
853 		deviceId = pci->read_pci_config(device, 2, 2);
854 		TRACE("Device ID after Ricoh quirk: %x\n", deviceId);
855 	}
856 
857 	return B_OK;
858 }
859 
860 
861 static void
862 uninit_device(void* device_cookie)
863 {
864 	// Get the PCI driver and device
865 	pci_device_module_info* pci;
866 	pci_device* device;
867 	uint16 vendorId, deviceId;
868 
869 	SdhciDevice* context = (SdhciDevice*)device_cookie;
870 	device_node* pciParent = gDeviceManager->get_parent_node(context->fNode);
871 	gDeviceManager->get_driver(pciParent, (driver_module_info**)&pci,
872 	        (void**)&device);
873 
874 	if (gDeviceManager->get_attr_uint16(context->fNode, B_DEVICE_VENDOR_ID,
875 			&vendorId, true) != B_OK
876 		|| gDeviceManager->get_attr_uint16(context->fNode, B_DEVICE_ID,
877 			&deviceId, false) != B_OK) {
878 		ERROR("No vendor or device id attribute\n");
879 	} else if (vendorId == 0x1180 && deviceId == 0xe823) {
880 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0xfc);
881 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE, 1,
882 			context->fRicohOriginalMode);
883 		pci->write_pci_config(device, SDHCI_PCI_RICOH_MODE_KEY, 1, 0);
884 	}
885 
886 	gDeviceManager->put_node(pciParent);
887 
888 	delete context;
889 }
890 
891 
892 static status_t
893 register_device(device_node* parent)
894 {
895 	device_attr attrs[] = {
896 		{B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {.string = "SD Host Controller"}},
897 		{}
898 	};
899 
900 	return gDeviceManager->register_node(parent, SDHCI_PCI_DEVICE_MODULE_NAME,
901 		attrs, NULL, NULL);
902 }
903 
904 
905 static float
906 supports_device(device_node* parent)
907 {
908 	const char* bus;
909 	uint16 type, subType;
910 	uint16 vendorId, deviceId;
911 
912 	// make sure parent is a PCI SDHCI device node
913 	if (gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false)
914 		!= B_OK) {
915 		TRACE("Could not find required attribute device/bus\n");
916 		return -1;
917 	}
918 
919 	if (strcmp(bus, "pci") != 0)
920 		return 0.0f;
921 
922 	if (gDeviceManager->get_attr_uint16(parent, B_DEVICE_VENDOR_ID, &vendorId,
923 			false) != B_OK
924 		|| gDeviceManager->get_attr_uint16(parent, B_DEVICE_ID, &deviceId,
925 			false) != B_OK) {
926 		TRACE("No vendor or device id attribute\n");
927 		return 0.0f;
928 	}
929 
930 	TRACE("supports_device(vid:%04x pid:%04x)\n", vendorId, deviceId);
931 
932 	if (gDeviceManager->get_attr_uint16(parent, B_DEVICE_SUB_TYPE, &subType,
933 			false) < B_OK
934 		|| gDeviceManager->get_attr_uint16(parent, B_DEVICE_TYPE, &type,
935 			false) < B_OK) {
936 		TRACE("Could not find type/subtype attributes\n");
937 		return -1;
938 	}
939 
940 	if (type == PCI_base_peripheral) {
941 		if (subType != PCI_sd_host) {
942 			// Also accept some compliant devices that do not advertise
943 			// themselves as such.
944 			if (vendorId != 0x1180
945 				|| (deviceId != 0xe823 && deviceId != 0xe822)) {
946 				TRACE("Not the right subclass, and not a Ricoh device\n");
947 				return 0.0f;
948 			}
949 		}
950 
951 		pci_device_module_info* pci;
952 		pci_device* device;
953 		gDeviceManager->get_driver(parent, (driver_module_info**)&pci,
954 			(void**)&device);
955 		TRACE("SDHCI Device found! Subtype: 0x%04x, type: 0x%04x\n",
956 			subType, type);
957 
958 		return 0.8f;
959 	}
960 
961 	return 0.0f;
962 }
963 
964 
965 static status_t
966 set_clock(void* controller, uint32_t kilohertz)
967 {
968 	SdhciBus* bus = (SdhciBus*)controller;
969 	bus->SetClock(kilohertz);
970 	return B_OK;
971 }
972 
973 
974 static status_t
975 execute_command(void* controller, uint8_t command, uint32_t argument,
976 	uint32_t* response)
977 {
978 	SdhciBus* bus = (SdhciBus*)controller;
979 	return bus->ExecuteCommand(command, argument, response);
980 }
981 
982 
983 static status_t
984 do_io(void* controller, uint8_t command, IOOperation* operation,
985 	bool offsetAsSectors)
986 {
987 	CALLED();
988 
989 	SdhciBus* bus = (SdhciBus*)controller;
990 	return bus->DoIO(command, operation, offsetAsSectors);
991 }
992 
993 
994 static void
995 set_scan_semaphore(void* controller, sem_id sem)
996 {
997 	CALLED();
998 
999 	SdhciBus* bus = (SdhciBus*)controller;
1000 	return bus->SetScanSemaphore(sem);
1001 }
1002 
1003 
1004 static void
1005 set_bus_width(void* controller, int width)
1006 {
1007 	CALLED();
1008 
1009 	SdhciBus* bus = (SdhciBus*)controller;
1010 	return bus->SetBusWidth(width);
1011 }
1012 
1013 
1014 module_dependency module_dependencies[] = {
1015 	{ MMC_BUS_MODULE_NAME, (module_info**)&gMMCBusController},
1016 	{ B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&gDeviceManager },
1017 	{}
1018 };
1019 
1020 
1021 // Device node registered for each SD slot. It implements the MMC operations so
1022 // the bus manager can use it to communicate with SD cards.
1023 static mmc_bus_interface gSDHCIPCIDeviceModule = {
1024 	{
1025 		{
1026 			SDHCI_PCI_MMC_BUS_MODULE_NAME,
1027 			0,
1028 			NULL
1029 		},
1030 		NULL,	// supports device
1031 		NULL,	// register device
1032 		init_bus,
1033 		uninit_bus,
1034 		NULL,	// register child devices
1035 		NULL,	// rescan
1036 		bus_removed,
1037 	},
1038 
1039 	set_clock,
1040 	execute_command,
1041 	do_io,
1042 	set_scan_semaphore,
1043 	set_bus_width
1044 };
1045 
1046 
1047 // Root device that binds to the PCI bus. It will register an mmc_bus_interface
1048 // node for each SD slot in the device.
1049 static driver_module_info sSDHCIDevice = {
1050 	{
1051 		SDHCI_PCI_DEVICE_MODULE_NAME,
1052 		0,
1053 		NULL
1054 	},
1055 	supports_device,
1056 	register_device,
1057 	init_device,
1058 	uninit_device,
1059 	register_child_devices,
1060 	NULL,	// rescan
1061 	NULL,	// device removed
1062 };
1063 
1064 
1065 module_info* modules[] = {
1066 	(module_info* )&sSDHCIDevice,
1067 	(module_info* )&gSDHCIPCIDeviceModule,
1068 	NULL
1069 };
1070