device.rs 23.7 KB
Newer Older
1 2
#![allow(dead_code)]

3
use std::{mem, thread, ptr, fmt};
4
use std::cmp;
5
use std::cmp::{max, min};
6
use std::ptr::copy_nonoverlapping;
7 8
use std::sync::Arc;
use std::cell::RefCell;
9 10 11 12 13
use std::collections::HashMap;
use std::str;
use std::string::String;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicUsize, Ordering};
14 15 16
extern crate syscall;


17 18
use syscall::MAP_WRITE;
use syscall::error::{Error, EACCES, EBADF, Result, EINVAL};
Nagy Tibor's avatar
Nagy Tibor committed
19 20
use syscall::flag::{SEEK_SET, SEEK_CUR, SEEK_END};
use syscall::io::{Mmio, Io};
21 22 23
use syscall::scheme::SchemeMut;

use spin::Mutex;
24 25 26 27 28 29

use super::BufferDescriptorListEntry;
use super::common::*;
use super::StreamDescriptorRegs;
use super::StreamBuffer;
use super::BitsPerSample;
30
use super::CommandBuffer;
31
use super::HDANode;
32
use super::OutputStream;
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

// GCTL - Global Control
const CRST:   u32 = 1 << 0; // 1 bit
const FNCTRL: u32 = 1 << 1; // 1 bit
const UNSOL:  u32 = 1 << 8; // 1 bit

// CORBCTL
const CMEIE:   u8 = 1 << 0; // 1 bit
const CORBRUN: u8 = 1 << 1; // 1 bit

// CORBSIZE
const CORBSZCAP: (u8,u8) = (4, 4);
const CORBSIZE:  (u8,u8) = (0, 2);

// CORBRP
const CORBRPRST: u16 = 1 << 15;

// RIRBWP
const RIRBWPRST: u16 = 1 << 15;

// RIRBCTL
const RINTCTL:   u8 = 1 << 0; // 1 bit
const RIRBDMAEN: u8 = 1 << 1; // 1 bit

// ICS
const ICB:      u16 = 1 << 0;
const IRV:      u16 = 1 << 1;


// CORB and RIRB offset

const COMMAND_BUFFER_OFFSET: usize = 0x40;


const NUM_SUB_BUFFS: usize = 2;
const SUB_BUFF_SIZE: usize = 0x4000;


71 72 73 74 75 76 77
enum Handle {
	Pcmout(usize, usize, usize), // Card, index, block_ptr
	Pcmin(usize, usize, usize),  // Card, index, block_ptr
	StrBuf(Vec<u8>,usize),
}


78 79

#[repr(packed)]
80
#[allow(dead_code)]
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
struct Regs {
	gcap:       Mmio<u16>,
	vmin:       Mmio<u8>,
	vmaj:       Mmio<u8>,
	outpay:     Mmio<u16>,
	inpay:      Mmio<u16>,
	gctl:       Mmio<u32>,
	wakeen:     Mmio<u16>,
	statests:   Mmio<u16>,
	gsts:       Mmio<u16>,
	rsvd0:      [Mmio<u8>;  6],
	outstrmpay: Mmio<u16>,
	instrmpay:  Mmio<u16>,
	rsvd1:      [Mmio<u8>;  4],
	intctl:     Mmio<u32>,
	intsts:     Mmio<u32>,
	rsvd2:      [Mmio<u8>;  8],
	walclk:     Mmio<u32>,
	rsvd3:      Mmio<u32>,
	ssync:      Mmio<u32>,
	rsvd4:      Mmio<u32>,

	corblbase:  Mmio<u32>,
	corbubase:  Mmio<u32>,
	corbwp:     Mmio<u16>,
	corbrp:     Mmio<u16>,
	corbctl:    Mmio<u8>,
	corbsts:    Mmio<u8>,
	corbsize:   Mmio<u8>,
	rsvd5:      Mmio<u8>,

	rirblbase:  Mmio<u32>,
	rirbubase:  Mmio<u32>,
	rirbwp:     Mmio<u16>,
	rintcnt:    Mmio<u16>,
	rirbctl:    Mmio<u8>,
	rirbsts:    Mmio<u8>,
	rirbsize:   Mmio<u8>,
	rsvd6:      Mmio<u8>,

	icoi:       Mmio<u32>,
	irii:       Mmio<u32>,
	ics:        Mmio<u16>,
	rsvd7:      [Mmio<u8>;  6],

	dplbase:    Mmio<u32>, // 0x70
	dpubase:    Mmio<u32>, // 0x74
	
}

pub struct IntelHDA {

133
	vend_prod: u32,
134

135 136
	base: usize,
	regs: &'static mut Regs,
137 138


139
	//corb_rirb_base_phys: usize,
140

141 142
	
	cmd: CommandBuffer,
143

144
	codecs: Vec<CodecAddr>,
145 146 147

	

148 149
	outputs: Vec<WidgetAddr>,
	inputs: Vec<WidgetAddr>,
150

151
	widget_map: HashMap<WidgetAddr, HDANode>,
152

153 154 155 156
	output_pins: Vec<WidgetAddr>,
	input_pins: Vec<WidgetAddr>,
	
	beep_addr: WidgetAddr,
157 158 159 160 161 162
	

	buff_desc: &'static mut [BufferDescriptorListEntry; 256],
	buff_desc_phys: usize,
	
	
163
	output_streams:         Vec<OutputStream>,
164 165 166 167

	buffs: Vec<Vec<StreamBuffer>>,

	int_counter: usize,
168 169
	handles: Mutex<BTreeMap<usize, Handle>>,
	next_id: AtomicUsize,
170 171 172 173
}


impl IntelHDA {
174
	pub unsafe fn new(base: usize, vend_prod:u32) -> Result<Self> {
175 176 177
	
		let regs = &mut *(base as *mut Regs);
		
178 179
		

180 181 182 183 184 185 186 187 188 189
		let buff_desc_phys = unsafe {
			syscall::physalloc(0x1000)
				.expect("Could not allocate physical memory for buffer descriptor list.")
		};

		
		let buff_desc_virt = unsafe { 
			syscall::physmap(buff_desc_phys, 0x1000, MAP_WRITE)
				.expect("ihdad: failed to map address for buffer descriptor list.") 
		};
190 191

		print!("Virt: {:016X}, Phys: {:016X}\n", buff_desc_virt, buff_desc_phys);
192 193 194 195 196 197
		

		let buff_desc = &mut *(buff_desc_virt as *mut [BufferDescriptorListEntry;256]);
		
		

198 199 200
		let cmd_buff_address = unsafe {
			syscall::physalloc(0x1000)
				.expect("Could not allocate physical memory for CORB and RIRB.")
201 202 203
		};

		
204
		let cmd_buff_virt = unsafe { syscall::physmap(cmd_buff_address, 0x1000, MAP_WRITE).expect("ihdad: failed to map address for CORB/RIRB buff") };
205

206
		print!("Virt: {:016X}, Phys: {:016X}\n", cmd_buff_virt, cmd_buff_address);
207
		let mut module = IntelHDA {
208
			vend_prod: vend_prod,
209 210
			base: base,
			regs: regs,
211 212
			
			cmd: CommandBuffer::new(base + COMMAND_BUFFER_OFFSET, cmd_buff_address, cmd_buff_virt),
213

214
			beep_addr: (0,0),
215
			
216 217 218 219
			widget_map: HashMap::<WidgetAddr, HDANode>::new(),


			codecs: Vec::<CodecAddr>::new(),
220
			
221 222 223 224 225
			outputs: Vec::<WidgetAddr>::new(),
			inputs: Vec::<WidgetAddr>::new(),

			output_pins: Vec::<WidgetAddr>::new(),
			input_pins: Vec::<WidgetAddr>::new(),
226 227 228 229

			buff_desc: buff_desc,
			buff_desc_phys: buff_desc_phys,

230 231 232 233


			output_streams: Vec::<OutputStream>::new(),

234 235 236 237 238

			buffs: Vec::<Vec<StreamBuffer>>::new(),


			int_counter: 0,
239 240
			handles: Mutex::new(BTreeMap::new()),
			next_id: AtomicUsize::new(0), 
241
		};
242
		
243
		module.init();
244 245
		
		// module.info();
246
		module.enumerate();
247 248
		
		module.configure();
249 250 251 252 253 254 255 256
		print!("IHDA: Initialization finished.\n");
		Ok(module)

	}

	pub fn init(&mut self) -> bool {
		self.reset_controller();

257 258 259 260 261
		let use_immediate_command_interface = match self.vend_prod {
			
			0x8086_2668 => false,
			_ => true,
		};	
262

263 264
		self.cmd.init(use_immediate_command_interface);	
		self.init_interrupts();
265 266 267 268 269 270 271 272 273
		
		true
	}

	pub fn init_interrupts(&mut self) {
		// TODO: provide a function to enable certain interrupts
		// This just enables the first output stream interupt and the global interrupt

		// TODO: No magic numbers! Bad Schemm.
274
		self.regs.intctl.write((1 << 31) | /* (1 << 30) |*/ (1 << 4));
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
	}


	

	pub fn irq(&mut self) -> bool {		
		self.int_counter += 1;
		
		self.handle_interrupts();

		true
	}

	pub fn int_count(&self) -> usize {
		self.int_counter
	}

292
	pub fn read_node(&mut self, addr: WidgetAddr) -> HDANode {
293 294 295 296
		let mut node = HDANode::new();
		let mut temp:u64;

		node.addr = addr;
297 298
		
		temp = self.cmd.cmd12( addr, 0xF00, 0x04);
299 300 301 302

		node.subnode_count = (temp & 0xff) as u16;
		node.subnode_start = ((temp >> 16) & 0xff) as u16;
		
303 304 305 306
		if addr == (0,0) {
			return node;
		}
		temp = self.cmd.cmd12(addr, 0xF00, 0x04);
307 308 309

		node.function_group_type = (temp & 0xff) as u8;

310
		temp = self.cmd.cmd12(addr, 0xF00, 0x09);
311 312 313
		node.capabilities = temp as u32;


314
		temp = self.cmd.cmd12(addr, 0xF00, 0x0E);
315 316 317 318 319

		node.conn_list_len = (temp & 0xFF) as u8;

		node.connections = self.node_get_connection_list(&node);
		
320 321 322

		node.config_default = self.cmd.cmd12(addr, 0xF1C, 0x00) as u32;

323 324 325 326
		node

	}

327 328 329
	pub fn node_get_connection_list(&mut self, node: &HDANode) -> Vec<WidgetAddr> {
		
		let len_field: u8 = (self.cmd.cmd12(node.addr, 0xF00, 0x0E) & 0xFF) as u8;
330 331 332 333 334 335 336 337 338
		
		// Highest bit is if addresses are represented in longer notation
		// lower 7 is actual count
			
		let count:u8 = len_field & 0x7F;
		let use_long_addr: bool = (len_field >> 7) & 0x1 == 1;
		
		let mut current: u8 = 0;
		
339
		let mut list = Vec::<WidgetAddr>::new();
340 341

		while current < count {
342 343
			
			let response: u32 = (self.cmd.cmd12(node.addr, 0xF02, current) & 0xFFFFFFFF) as u32;
344 345 346 347 348 349 350 351 352
			
			if use_long_addr {
				for i in 0..2 {
					let addr_field = ((response >> (16 * i)) & 0xFFFF) as u16;
					let addr = (addr_field & 0x7FFF);

					if addr == 0 { break; }
					
					if (addr_field >> 15) & 0x1 == 0x1 {
353 354
						for i in (list.pop().unwrap().1 .. (addr + 1)) {
							list.push((node.addr.0, i));
355 356
						}
					} else {
357
						list.push((node.addr.0, addr));
358 359 360 361 362 363 364 365 366 367 368 369
					}
				}

			} else {

				for i in 0..4 {
					let addr_field = ((response >> (8 * i)) & 0xff) as u16;
					let addr = (addr_field & 0x7F);
					
					if addr == 0 { break; }				

					if (addr_field >> 7) & 0x1 == 0x1 {
370 371
						for i in (list.pop().unwrap().1 .. (addr + 1)) {
							list.push((node.addr.0, i));
372 373
						}
					} else {
374
						list.push((node.addr.0, addr));
375 376 377 378 379 380 381 382 383 384 385 386 387
					}
				}

			}
			
			current = list.len() as u8;

		}
		list
		
	}
	pub fn enumerate(&mut self) {

388

389 390 391
		self.output_pins.clear();
		self.input_pins.clear();

392 393

		let codec:u8 = 0;
394
		
395
		let root = self.read_node((codec,0));
396 397 398 399 400 401 402 403 404
		
		// print!("{}\n", root);

		let root_count = root.subnode_count;
		let root_start = root.subnode_start;
		

		//FIXME: So basically the way this is set up is to only support one codec and hopes the first one is an audio
		for i in 0..root_count { 
405
			let afg = self.read_node((codec, root_start + i));
406 407 408 409 410
			// print!("{}\n", afg);
			let afg_count = afg.subnode_count;
			let afg_start = afg.subnode_start;
			
			for j in 0..afg_count {
411 412
				
				let mut widget = self.read_node((codec, afg_start + j));
413 414
				widget.is_widget = true;
				match widget.widget_type() {
415 416
					HDAWidgetType::AudioOutput => {self.outputs.push(widget.addr)},
					HDAWidgetType::AudioInput  => {self.inputs.push(widget.addr)},
417
					HDAWidgetType::BeepGenerator => {self.beep_addr = widget.addr },
418 419 420 421 422 423 424 425 426 427 428 429
					HDAWidgetType::PinComplex => {
						let config = widget.configuration_default();
						if config.is_output() {
							self.output_pins.push(widget.addr);
						} else if (config.is_input()) {
							self.input_pins.push(widget.addr);
						}


						print!("{:02X}{:02X} {}\n", widget.addr().0, widget.addr().1, config);
						
					},
430 431
					_ => {},
				}
432 433 434
				
				print!("{}\n", widget);
				self.widget_map.insert(widget.addr(), widget);
435 436 437 438
			}	
		}
	}

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	


	pub fn find_best_output_pin(&self) -> Option<WidgetAddr>{
		let outs = &self.output_pins;
		if outs.len() == 0 {
			None
		} else if outs.len() == 1 {
			Some(outs[0])
		} else {
			// TODO: Somehow find the best.
			// Slightly okay is find the speaker with the lowest sequence number.
						
			for &out in outs {
				let widget = self.widget_map.get(&out).unwrap();
				
				let cd = widget.configuration_default();
				if cd.sequence() == 0 && cd.default_device() == DefaultDevice::Speaker {
					return Some(out);
				}
459 460
			}

461
			None
462 463 464
		}
	}

465
	
466

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
	pub fn find_path_to_dac(&self, addr: WidgetAddr) -> Option<Vec<WidgetAddr>>{
		let widget = self.widget_map.get(&addr).unwrap();
		if widget.widget_type() == HDAWidgetType::AudioOutput {
			return Some(vec![addr]);
		}else{
			if widget.connections.len() == 0 {
				return None;
			}else{
				// TODO: do more than just first widget

				let mut res = self.find_path_to_dac(widget.connections[0]);
				match res {
					Some(p) => {
						let mut ret = p.clone();
						ret.insert(0, addr);
						Some(ret)
					},
					None => {None},
				}
			}
487

488 489
		}
	} 
490 491


492 493
	
	
494 495 496 497 498 499 500 501
	/*
	  Here we update the buffers and split them into 128 byte sub chunks
	  because each BufferDescriptorList needs to be 128 byte aligned,
	  this makes it so each of the streams can have up to 128/16 (8) buffer descriptors
	*/
	/*
	  Vec of a Vec was doing something weird and causing the driver to hang.
	  So now we have a set of variables instead.
502 503 504


	  Fixed?
505
	*/
506
	
507 508 509 510 511 512 513 514 515 516
	pub fn update_sound_buffers(&mut self) {
		/*
		for i in 0..self.buffs.len(){
			for j in 0.. min(self.buffs[i].len(), 128/16 ) {
				self.buff_desc[i * 128/16 + j].set_address(self.buffs[i][j].phys());
				self.buff_desc[i * 128/16 + j].set_length(self.buffs[i][j].length() as u32);
				self.buff_desc[i * 128/16 + j].set_interrupt_on_complete(true);
			}
		}*/

517
		let r = self.get_output_stream_descriptor(0).unwrap();
518 519

		
520
		self.output_streams.push(OutputStream::new(2, 0x4000, r));
521

522
		let o = self.output_streams.get_mut(0).unwrap();
523 524


525 526 527
		self.buff_desc[0].set_address(o.phys());
		self.buff_desc[0].set_length(o.block_size() as u32);
		self.buff_desc[0].set_interrupt_on_complete(true);		
528 529

		
530 531 532
		self.buff_desc[1].set_address(o.phys() + o.block_size());
		self.buff_desc[1].set_length(o.block_size() as u32);
		self.buff_desc[1].set_interrupt_on_complete(true);
533 534
		

535
	}
536 537 538 539


	

540 541 542
	pub fn configure(&mut self) {
		
		let outpin = self.find_best_output_pin().expect("IHDA: No output pins?!");
543
		
544
		//print!("Best pin: {:01X}:{:02X}\n", outpin.0, outpin.1);
545

546
		let path = self.find_path_to_dac(outpin).unwrap();
547

548 549
		let dac = *path.last().unwrap();
		let pin = *path.first().unwrap();
550

551
		//print!("Path to DAC: {:?}\n", path);
552

553 554 555
		// Pin enable
		self.cmd.cmd12(pin, 0x707, 0x40);
		
556

557 558
		// EAPD enable
		self.cmd.cmd12(pin, 0x70C, 2);
559

560
		self.set_stream_channel(dac, 1, 0);
561 562 563 564

		self.update_sound_buffers();


565 566
		//print!("Supported Formats: {:08X}\n", self.get_supported_formats((0,0x1)));
		//print!("Capabilities: {:08X}\n", self.get_capabilities(path[0]));
567 568 569

		let output = self.get_output_stream_descriptor(0).unwrap();
		
570 571
		
		
572 573
		output.set_address(self.buff_desc_phys);

574

575
		output.set_pcm_format(&super::SR_44_1, BitsPerSample::Bits16, 2);
576
		output.set_cyclic_buffer_length(0x8000); // number of bytes
577 578 579 580 581
		output.set_stream_number(1);
		output.set_last_valid_index(1);
		output.set_interrupt_on_completion(true);


582 583
		self.set_power_state(dac, 0); // Power state 0 is fully on
		self.set_converter_format(dac, &super::SR_44_1, BitsPerSample::Bits16, 2);
584 585
		
		
586
		self.cmd.cmd12(dac, 0xA00, 0);
587 588

		// Unmute and set gain for pin complex and DAC
589 590 591 592 593 594 595 596 597 598 599 600 601
		self.set_amplifier_gain_mute(dac, true, true, true, true, 0, false, 0x7f);
		self.set_amplifier_gain_mute(pin, true, true, true, true, 0, false, 0x7f);

		output.run();
		
	}
	/*

	pub fn configure_vbox(&mut self) {
		
		let outpin = self.find_best_output_pin().expect("IHDA: No output pins?!");
		
		print!("Best pin: {:01X}:{:02X}\n", outpin.0, outpin.1);
602

603 604
		let path = self.find_path_to_dac(outpin).unwrap();
		print!("Path to DAC: {:?}\n", path);
605

606 607
		// Pin enable
		self.cmd.cmd12((0,0xC), 0x707, 0x40);
608 609
		

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
		// EAPD enable
		self.cmd.cmd12((0,0xC), 0x70C, 2);

		self.set_stream_channel((0,0x3), 1, 0);

		self.update_sound_buffers();


		print!("Supported Formats: {:08X}\n", self.get_supported_formats((0,0x1)));
		print!("Capabilities: {:08X}\n", self.get_capabilities((0,0x1)));

		let output = self.get_output_stream_descriptor(0).unwrap();
		
		output.set_address(self.buff_desc_phys);

		output.set_pcm_format(&super::SR_44_1, BitsPerSample::Bits16, 2);
		output.set_cyclic_buffer_length(0x8000); 
		output.set_stream_number(1);
		output.set_last_valid_index(1);
		output.set_interrupt_on_completion(true);


		self.set_power_state((0,0x3), 0); // Power state 0 is fully on
		self.set_converter_format((0,0x3), &super::SR_44_1, BitsPerSample::Bits16, 2);
		
		
		self.cmd.cmd12((0,0x3), 0xA00, 0);

		// Unmute and set gain for pin complex and DAC
		self.set_amplifier_gain_mute((0,0x3), true, true, true, true, 0, false, 0x7f);
		self.set_amplifier_gain_mute((0,0xC), true, true, true, true, 0, false, 0x7f);
641 642 643 644 645 646

		output.run();

		self.beep(1);
		
	}
647 648
	
	*/
649 650 651 652

	// BEEP!!
	pub fn beep(&mut self, div:u8) {
		let addr = self.beep_addr;
653 654 655
		if addr != (0,0) {
			
			let _ = self.cmd.cmd12(addr, 0xF0A, div);
656 657 658 659 660 661 662
			
		}

	}
	
	pub fn read_beep(&mut self) -> u8 {
		let addr = self.beep_addr;
663 664 665
		if addr != (0,0) {

			self.cmd.cmd12(addr, 0x70A, 0) as u8
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
		}else{
			0
		}

	}

	pub fn reset_controller(&mut self) -> bool {

		self.regs.statests.write(0xFFFF);

		// 3.3.7
		self.regs.gctl.writef(CRST, false);
		loop {
			if ! self.regs.gctl.readf(CRST) {
				break;
			}
		}
		self.regs.gctl.writef(CRST, true);
		loop {
			if self.regs.gctl.readf(CRST) {
				break;
			}
		}

		let mut ticks:u32 = 0;
		while self.regs.statests.read() == 0 {
			ticks += 1;
			if ticks > 10000 { break;}

		}

		let statests = self.regs.statests.read();
698
		print!("Statests: {:04X}\n", statests);
699 700 701

		for i in 0..15 {
			if (statests >> i) & 0x1 == 1 {
702
				self.codecs.push(i as CodecAddr);
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
			} 
		}
		true

	}
	
	pub fn num_output_streams(&self) -> usize{
		let gcap = self.regs.gcap.read();
		((gcap >> 12) & 0xF) as usize
	}
	
	pub fn num_input_streams(&self) -> usize{
		let gcap = self.regs.gcap.read();
		((gcap >> 8) & 0xF) as usize
	}

	pub fn num_bidirectional_streams(&self) -> usize{
		let gcap = self.regs.gcap.read();
		((gcap >> 3) & 0xF) as usize
	}

	pub fn num_serial_data_out(&self) -> usize{
		let gcap = self.regs.gcap.read();
		((gcap >> 1) & 0x3) as usize
	}

	pub fn info(&self) {
		print!("Intel HD Audio Version {}.{}\n", self.regs.vmaj.read(), self.regs.vmin.read());
		print!("IHDA: Input Streams: {}\n", self.num_input_streams());
		print!("IHDA: Output Streams: {}\n", self.num_output_streams());
		print!("IHDA: Bidirectional Streams: {}\n", self.num_bidirectional_streams());
		print!("IHDA: Serial Data Outputs: {}\n", self.num_serial_data_out());
		print!("IHDA: 64-Bit: {}\n", self.regs.gcap.read() & 1 == 1);
	}

	

740
	fn get_input_stream_descriptor(&self, index: usize) -> Option<&'static mut StreamDescriptorRegs> {
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
		unsafe {
			if index < self.num_input_streams() {
				Some(&mut *((self.base + 0x80 + index * 0x20) as *mut StreamDescriptorRegs))
			}else{
				None
			}
		}
	}

	fn get_output_stream_descriptor(&self, index: usize) -> Option<&'static mut StreamDescriptorRegs> {
		unsafe {
			if index < self.num_output_streams() {
				Some(&mut *((self.base + 0x80 + 
							self.num_input_streams() * 0x20 +
							index * 0x20) as *mut StreamDescriptorRegs))
			}else{
				None
			}
		}
	}


	fn get_bidirectional_stream_descriptor(&self, index: usize) -> Option<&'static mut StreamDescriptorRegs> {
		unsafe {
			if index < self.num_bidirectional_streams() {
				Some(&mut *((self.base + 0x80 + 
							self.num_input_streams() * 0x20 +
							self.num_output_streams() * 0x20 +
							index * 0x20) as *mut StreamDescriptorRegs))
			}else{
				None
			}
		}
	}

	fn set_dma_position_buff_addr(&mut self, addr: usize) {
		let addr_val = addr & !0x7F;
		self.regs.dplbase.write((addr_val & 0xFFFFFFFF) as u32);
		self.regs.dpubase.write((addr_val >> 32) as u32);
	}


783
	fn set_stream_channel(&mut self, addr: WidgetAddr, stream: u8, channel:u8) {
784
		let val = ((stream & 0xF) << 4) | (channel & 0xF);
785
		self.cmd.cmd12(addr, 0x706, val);
786 787
	}

788 789
	fn set_power_state(&mut self, addr:WidgetAddr, state:u8) {
		self.cmd.cmd12(addr, 0x705, state & 0xF) as u32;
790 791
	}

792 793
	fn get_supported_formats(&mut self, addr: WidgetAddr) -> u32 {
		self.cmd.cmd12(addr, 0xF00, 0x0A) as u32
794 795
	}

796 797
	fn get_capabilities(&mut self, addr: WidgetAddr) -> u32 {
		self.cmd.cmd12(addr, 0xF00, 0x09) as u32
798 799
	}

800
	fn set_converter_format(&mut self, addr:WidgetAddr, sr: &super::SampleRate, bps: BitsPerSample, channels:u8) {
801
		let fmt = super::format_to_u16(sr, bps, channels);
802
		self.cmd.cmd4(addr, 0x2, fmt);
803 804
	}

805 806 807
	

	fn set_amplifier_gain_mute(&mut self, addr: WidgetAddr, output:bool, input:bool, left:bool, right:bool, index:u8, mute:bool, gain: u8) {
808 809 810 811 812 813 814 815 816 817 818

		let mut payload: u16 = 0;
		
		if output { payload |= (1 << 15); }
		if input  { payload |= (1 << 14); }
		if left   { payload |= (1 << 13); }
		if right  { payload |= (1 << 12); }
		if mute   { payload |= (1 <<  7); }
		payload |= ((index as u16) & 0x0F) << 8;
		payload |= ((gain  as u16) & 0x7F);

819 820 821
		self.cmd.cmd4(addr, 0x3, payload);

	
822 823
	}

824
	pub fn write_to_output(&mut self, index:u8, buf: &[u8]) -> Result<usize> {
825

826 827 828
		let mut output = self.get_output_stream_descriptor(index as usize).unwrap();
		let mut os = self.output_streams.get_mut(index as usize).unwrap();
		
829 830 831
		
		
		let sample_size:usize = output.sample_size();
832
		let mut open_block = (output.link_position() as usize) / os.block_size();
833 834 835 836 837 838 839 840 841 842



				
		if open_block == 0 {
			open_block = 1;
		} else {
			open_block = open_block - 1;
		}

843 844
		//print!("Status: {:02X} Pos: {:08X} Output CTL: {:06X}\n", output.status(), output.link_position(), output.control());
		while open_block == os.current_block() {
845

846
			open_block = (output.link_position() as usize) / os.block_size();
847 848
				
			if open_block == 0 {
849
				open_block = os.block_count() - 1;
850 851 852
			} else {
				open_block = open_block - 1;
			}
853 854
			
			
855 856 857
			thread::yield_now();
		}
		
858
		let len = min(os.block_size(), buf.len());
859
		
860
		os.write_block(buf)
861 862 863 864 865 866
	}

	pub fn handle_interrupts(&mut self) {

		let intsts = self.regs.intsts.read();
		let sis = intsts & 0x3FFFFFFF;      
867
		// print!("IHDA INTSTS: {:08X}\n", intsts);     
868 869 870 871 872 873 874 875 876 877 878 879
		if ((intsts >> 31) & 1) == 1 {           // Global Interrupt Status
			if ((intsts >> 30) & 1) == 1 {   // Controller Interrupt Status
				self.handle_controller_interrupt();
			} 

			if sis != 0 {
				self.handle_stream_interrupts(sis);
			}
		}
	}

	pub fn handle_controller_interrupt(&mut self) {
880
		
881 882 883 884 885 886 887 888 889
	}

	pub fn handle_stream_interrupts(&mut self, sis: u32) {
		let oss = self.num_output_streams();
		let iss = self.num_input_streams();
		let bss = self.num_bidirectional_streams();

		for i in 0..iss {
			if ((sis >> i) & 1 ) == 1 {
890 891
				let mut input = self.get_input_stream_descriptor(i).unwrap();	
				input.clear_interrupts();
892 893 894 895 896 897 898 899 900 901 902 903
			}
		}

		for i in 0..oss {
			if ((sis >> (i + iss)) & 1 ) == 1 {
				let mut output = self.get_output_stream_descriptor(i).unwrap();	
				output.clear_interrupts();
			}
		}

		for i in 0..bss {
			if ((sis >> (i + iss + oss)) & 1 ) == 1 {
904 905
				let mut bid = self.get_bidirectional_stream_descriptor(i).unwrap();	
				bid.clear_interrupts();
906 907 908 909
			}
		}
	}
	
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
	fn validate_path(&mut self, path: &Vec<&str>) -> bool {

		print!("Path: {:?}\n", path);
		let mut it = path.iter();
		match it.next() {
			Some(card_str) if (*card_str).starts_with("card") => {	
				match usize::from_str_radix(&(*card_str)[4..], 10) {
					Ok(card_num) => {
						print!("Card# {}\n", card_num);
						match it.next() {
							Some(codec_str) if (*codec_str).starts_with("codec#") => {	
								match usize::from_str_radix(&(*codec_str)[6..], 10) {
									Ok(codec_num) => {

										let id = self.next_id.fetch_add(1, Ordering::SeqCst);
                    								//self.handles.lock().insert(id, Handle::Disk(disk.clone(), 0));
										true

									},
									_ => false,
								}	
							},
							Some(pcmout_str) if (*pcmout_str).starts_with("pcmout") => {	
								match usize::from_str_radix(&(*pcmout_str)[6..], 10) {
									Ok(pcmout_num) => {
										print!("pcmout {}\n", pcmout_num);
										true
									},
									_ => false,
								}	
							},
							Some(pcmin_str) if (*pcmin_str).starts_with("pcmin") => {	
								match usize::from_str_radix(&(*pcmin_str)[6..], 10) {
									Ok(pcmin_num) => {
										print!("pcmin {}\n", pcmin_num);
										true
									},
									_ => false,
								}	
							},
							_ => false,
						}
					},
					_ => false,
				}	
			},
			Some(cards_str) if *cards_str == "cards" => {
				true
			},
			_ => false,	
		}
	}	
962 963 964 965 966 967 968 969 970 971 972 973
}


impl Drop for IntelHDA {
	fn drop(&mut self) {
		print!("IHDA: Deallocating IHDA driver.\n");

	}
}


impl SchemeMut for IntelHDA {
974 975 976

	

977
	fn open(&mut self, _path: &[u8], flags: usize, uid: u32, _gid: u32) -> Result<usize> {
978 979 980 981 982 983 984 985 986 987 988 989
		let path: Vec<&str>;
		/*
		match str::from_utf8(_path) {
			Ok(p)  => {
					path = p.split("/").collect();
					if !self.validate_path(&path) {
						return Err(Error::new(EINVAL));
					
				},
			Err(_) => {return Err(Error::new(EINVAL));},
		}*/
		
990
		
991 992
		

993 994
		// TODO:
		if uid == 0 {
Nagy Tibor's avatar
Nagy Tibor committed
995
			Ok(0)
996 997 998 999 1000 1001 1002 1003 1004 1005
		} else {
			Err(Error::new(EACCES))
		}
	}

	fn write(&mut self, _id: usize, buf: &[u8]) -> Result<usize> {
	
		//print!("Int count: {}\n", self.int_counter);
		

1006
		self.write_to_output(0, buf)
1007 1008
	}

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
	fn seek(&mut self, id: usize, pos: usize, whence: usize) -> Result<usize> {
		let mut handles = self.handles.lock();
		match *handles.get_mut(&id).ok_or(Error::new(EBADF))? {
			Handle::StrBuf(ref mut strbuf, ref mut size) => {
				let len = strbuf.len() as usize;
				*size = match whence {
					SEEK_SET => cmp::min(len, pos),
					SEEK_CUR => cmp::max(0, cmp::min(len as isize, *size as isize + pos as isize)) as usize,
					SEEK_END => cmp::max(0, cmp::min(len as isize,   len as isize + pos as isize)) as usize,
					_ => return Err(Error::new(EINVAL))
				};
				Ok(*size)
			},
	            
			_ => Err(Error::new(EINVAL)),
	        }
    	}


1028
	fn close(&mut self, _id: usize) -> Result<usize> {
1029 1030
		let mut handles = self.handles.lock();
        	handles.remove(&_id).ok_or(Error::new(EBADF)).and(Ok(0))
1031 1032
    	}

Nagy Tibor's avatar
Nagy Tibor committed
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    fn fpath(&mut self, id: usize, buf: &mut [u8]) -> Result<usize> {
        //let mut handles = self.handles.lock();
        //let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?;

        let mut i = 0;
        let scheme_path = b"audio:";
        while i < buf.len() && i < scheme_path.len() {
            buf[i] = scheme_path[i];
            i += 1;
        }
        Ok(i)
    }
Nagy Tibor's avatar
Nagy Tibor committed
1045
}