/*
 * txt_rs232.c - RS232 driver implementation
 *
 * Copyright (c) 2017 Maxime Villard
 *
 * This file is part of ALMOS-MKH.
 *
 * ALMOS-MKH is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2.0 of the License.
 *
 * ALMOS-MKH is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ALMOS-MKH; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <dev_txt.h>
#include <chdev.h>
#include <txt_rs232.h>
#include <remote_spinlock.h>
#include <thread.h>
#include <hal_special.h>

#include <hal_internal.h> // XXX

void txt_rs232_init(chdev_t *chdev)
{
	chdev->cmd = &txt_rs232_cmd;
	chdev->isr = &txt_rs232_isr;

	// nothing to do
}

// Pour le write: tout en sync, ça part direct sur le VGA/série
// Pour le read: là on attend l'ISR
void txt_rs232_cmd(xptr_t th_xp)
{
	// get client thread cluster and local pointer
	cxy_t      th_cxy = GET_CXY( th_xp );
	thread_t * th_ptr = (thread_t *)GET_PTR( th_xp );

	// get command type and extended pointer on TXT device
	uint32_t type   =         hal_remote_l32 ( XPTR( th_cxy , &th_ptr->txt_cmd.type ) );
	xptr_t   dev_xp = (xptr_t)hal_remote_l64( XPTR( th_cxy , &th_ptr->txt_cmd.dev_xp ) );

	// get TXT device cluster and local pointer
	cxy_t     dev_cxy = GET_CXY( dev_xp );
	chdev_t * dev_ptr = (chdev_t *)GET_PTR( dev_xp );

	// get TTY channel index
	uint32_t   channel = hal_remote_l32( XPTR( dev_cxy , &dev_ptr->channel ) );

	// for now, only channel zero
	if (channel != 0) {
		x86_panic("should have been channel zero");
	}

	if (type == TXT_READ)              // descheduling strategy for calling thread
	{
		x86_panic("TXT_READ not handled");
	}
	else if (type == TXT_WRITE || type == TXT_SYNC_WRITE) // busy waiting strategy for calling thread
	{
		uint32_t   i;

		// get source buffer extended pointer & bytes count
		uint32_t count  = hal_remote_l32 ( XPTR( th_cxy , &th_ptr->txt_cmd.count ) );
		xptr_t   buf_xp = hal_remote_l64( XPTR( th_cxy , &th_ptr->txt_cmd.buf_xp ) );

		// loop on characters
		for (i = 0; i < count; i++)
		{
			// get one byte from command buffer in client cluster
			char byte = (char)hal_remote_lb( buf_xp + i );

			// VGA output (for now)
			x86_putc(byte);
		}
	}
}

void txt_rs232_isr(chdev_t *chdev)
{
	// Cette ISR est juste utile pour le clavier; on arrive ici quand une touche
	// est pressée
	x86_panic("txt_rs232_isr not handled");
}

