#include <linux/config.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include "ax25.h"
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include "sock.h"
#include <asm/segment.h>
#include <asm/system.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>

#ifdef CONFIG_AX25
/*
 * Copyright (c) University of British Columbia, 1984
 * Copyright (c) 1990 The Regents of the University of California.
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * the Laboratory for Computation Vision and the Computer Science Department
 * of the University of British Columbia.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)hd_output.c	7.6 (Berkeley) 5/29/91
 */


/*
 *      HDLC OUTPUT INTERFACE
 *
 *      This routine is called when the AX.25 packet layer output routine
 *      has a information frame (iframe)  to write.   It is  also called 
 *      by the input and control routines of the HDLC layer.
 */



int ax25_output(ax25_socket *sk,sk_buff *skb)
{
	skb_queue_tail(&sk->write_queue, skb);	/* Throw it on the queue */
	ax25_kick(sk);				/* See if we can transmit anything */
	return 0;
}

void ax25_kick(ax25_socket *sk)
{
	sk_buff *skb;	
	/* 
	 * The iframe is only transmitted if all these conditions are FALSE.
	 * The iframe remains queued (sk->wfront) however and will be
	 * transmitted as soon as these conditions are cleared.
	 */

	while (!(sk->opt.ax25.condition & (TIMER_RECOVERY_CONDITION | REMOTE_RNR_CONDITION))) {
		if (sk->opt.ax25.vs == (sk->opt.ax25.lastrxnr + sk->window/*7*/) % MODULUS) 
		{

			/* We have now exceeded the  maximum  number  of 
			   outstanding iframes. Therefore,  we must wait 
			   until  at least  one is acknowledged if this 
			   condition  is not  turned off before we are
			   requested to write another iframe. */
			if(sk->debug)
				printk("No window.\n");
			break;
		}

		/* Remove top iframe from transmit queue. */
		if ((skb = skb_dequeue(&sk->write_queue)) == NULL)
		{
			if(sk->debug)
				printk("Queue emptied\n");
			break;
		}

		/* Kick it out */
		ax25_send_iframe(sk, skb, POLLOFF);
	}
}

/* 
 *  This procedure is passed a buffer descriptor for an iframe. It builds
 *  the rest of the control part of the frame and then writes it out.  It
 *  also  starts the  acknowledgement  timer and keeps  the iframe in the
 *  Retransmit queue (Retxq) just in case  we have to do this again.
 *
 *  Note: This routine is also called from ax25_in.c when retransmission
 *       of old frames is required.
 */

void ax25_send_iframe(ax25_socket *sk, sk_buff *skb, int poll_bit)
{
	struct Hdlc_iframe *iframe;
	KILL_TIMER (sk);

	if(sk->debug)
		printk("SendIFrame: %p %p p=%d used=%ld\n",sk,skb,poll_bit,sk->wmem_alloc);
	if (skb == NULL) 
	{
		sk->opt.ax25.vs = (sk->opt.ax25.vs + 7) % MODULUS;
		SET_TIMER(sk);
		return;
	}
	
	iframe = (struct Hdlc_iframe *)(skb->h.raw);	/* KISS + header */

	iframe -> address = AX25_P_TEXT;
	iframe -> hdlc_0 = 0;
	iframe -> nr = sk->opt.ax25.vr;
	iframe -> pf = poll_bit;
	iframe -> ns = sk->opt.ax25.vs;
	
	if(sk->debug)
		printk("SendIFrame: NR=%d NS=%d\n",sk->opt.ax25.vr,sk->opt.ax25.vs);
		
	sk->opt.ax25.lasttxnr = sk->opt.ax25.vr;
	sk->opt.ax25.rrtimer = 0;

	if (sk->opt.ax25.vs == sk->opt.ax25.retxqi) {
		/* Check for retransmissions. */
		/* Put iframe only once in the Retransmission queue. */
		sk->opt.ax25.retxq[(int)sk->opt.ax25.retxqi] = skb;
		sk->opt.ax25.retxqi = (sk->opt.ax25.retxqi + 1) % MODULUS;
	}

	sk->opt.ax25.vs = (sk->opt.ax25.vs + 1) % MODULUS;


	skb->free=0;			/* Dont free on handle recovery */	
	ax25_transmit_buffer(sk,skb,C_COMMAND, 0);	

	/* Done */
	SET_TIMER (sk);
}

/* 
 *  This routine gets control when the timer expires because we have not
 *  received an acknowledgement for a iframe.
 */

void ax25_resend_iframe(ax25_socket *sk)
{

	if (sk->opt.ax25.retxcnt++ < (signed int)sk->opt.ax25.n2) {
		if (!(sk->opt.ax25.condition & TIMER_RECOVERY_CONDITION)) {
			sk->opt.ax25.xx = sk->opt.ax25.vs;
			sk->opt.ax25.condition |= TIMER_RECOVERY_CONDITION;
		}
		/* Ok kick it out and off we go */
		sk->opt.ax25.vs = sk->opt.ax25.lastrxnr;
		ax25_send_iframe(sk, sk->opt.ax25.retxq[(int)sk->opt.ax25.vs], POLLON);
	} else {
		/* At this point we have not received a RR even after N2
		   retries - attempt to reset link. */

		ax25_init_vars(sk);
		ax25_write_internal (sk, DM, POLLOFF, C_COMMAND);
		if(sk->debug)
			printk("LAPB: IFrame retransmit timed out.\n");
		sk->opt.ax25.state = DISCONNECTED;
		sk->state=TCP_CLOSE;
		sk->err=ETIMEDOUT;
		if(!sk->dead)
			sk->state_change(sk);
		SET_TIMER (sk);
	}
}

void ax25_transmit_buffer(ax25_socket *sk, sk_buff *skb,int type, int add_address)
{
	struct protocol *proto=ax25rtr_get_dev(&sk->opt.ax25.source_addr);
	if(proto==NULL)	/* oops.. */
	{
		sk->err=ENETUNREACH;
		sk->error_report(sk);
		return;
	}
	if(add_address)
		build_ax25_addr(skb,&sk->opt.ax25.source_addr,&sk->opt.ax25.dest_addr,sk->opt.ax25.digipeat,type);
	if(sk->debug==1)
	{
		int l=0;
		unsigned char *data=skb_data(skb);
		printk("ax25_transmit: %ld bytes.\n",skb->len);
		while(l<skb->len)
		{
			printk("%02x",data[l]);
			l++;
			if(l%10==0)
				printk("\n");
			else
				printk(" ");
		}
		if(l%10)
			printk("\n");
	}
	/* Until we put some sanity checking in here we can't have people priority jumping certain
	   types of connection as LAPB doesn't allow packet re-ordering to occur! */
	skb->priority=SOPRI_NORMAL;
	proto->output(proto,skb,ETH_P_AX25, 0, NULL, NULL, NULL);
}
	
#endif
