BSD net源码分析(3)──SLIP接口

LwIP 之二 网络接口 netif(netif.c、ethernetif.c、slipif.c)、多网口处理 LwIP 使用 struct netif 来描述一个硬件网络接口。netif 是 LwIP 抽象出来的各网络接口,协议栈可以使用多个不同的接口,而 ./src/netif/ethernet.c、./src/netif/slipif.c 就提供了netif 访问硬件的各接口。 阅读详情

一、SLIP接口概述
SLIP接口通过一个标准的异步串行线与一个远程系统通信。通过SLIP帧为上层承载IP分组。
每个分组使用0xc0来隔开,如果分组中出现该字符,需要该字符前填充字符0xdb,并将该字符转换为0xdc。如果字符中出现0xdb,在字符前填充0xdb,并替换字符为0xdd。

SLIP接口依靠一个异步串行设备驱动器来发送和接收数据,驱动器称为tty。tty子系统包括一个线路规程(Line discipline)。这个线程作为物理设备和I/O系统调用(read和write)之间的过滤器。
一个线路规程实现以下的特性:如行编辑、换行和回车处理、制表符扩展等等。
SLIP接口作为tty子系统的一个线路规程,但它不把输入数据传给从设备读取数据的进程,也不接受来自设备写数据的进程的输出数据。SLIP接口将输入分组传给IP输入队列,并通过SLIP的ifnet结构的if_output来获得要输出的分组。内核通过一个整数常量来标识线路规程,对于SLIP,该常量是SLIPDISC。

函   数     网络接口 线路规程                   说  明
                         
slattach   •                    初始化s l _ s o f t c结构,并将它连接到 i f n e t列表
slinit         •                    初始化SLIP数据结构
sloutput   •                    对相关TTY设备上要传输的输出分组进行排队
slioctl       •                    处理插口i o c t l请求
sl_btom    •                    将一个设备缓存转换成一个 m b u f链表
slopen             •             将s l _ s o f t c结构连接到 TTY设备,并初始化驱动程序
slclose             •             取消TTY设备与s l _ s o f t c结构的连接,标记接口为关闭,并释放存储器
sltioctl             •             处理TTY i o c t l命令
slstart     •       •             从队列中取分组,并开始在 TTY设备上传输数据
slinput     •       •             处理从TTY设备输入的字节,如果整个帧被接收,就排列输入的分组

二、SLIP接口初始化
SLIP接口的驱动入口函数只有两个,if_output指向sloutput,用于接收将要传输的分组进行排队,if_ioctl指向slioctl,用于从一个进程控制控制接口。
/**********************************/
/* Attach pseudo-devices. */
    for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
        (*pdev->pdev_attach)(pdev->pdev_count);

    /*
     * Initialize protocols.  Block reception of incoming packets
     * until everything is ready.
     */
    s = splimp();
    ifinit();
    domaininit();
    splx(s);
/**********************************/
SLIP和环回接口,通过软件实现,而不通过内核发现硬件,中断触发进行初始化。
这些伪设备通过一个全局变量pdevinit存储。
/*************************************/
/*
 * Pseudo-device attach information (function + number of pseudo-devs).
 */
struct pdevinit {
    void    (*pdev_attach) __P((int));
    int    pdev_count;
};
/*************************************/
pdev_attach 指向初始化的函数
pdev_count 接口的个数
初始化SLIP接口时,pdev_attach指向函数slattach()。
和以太网接口一样,SLIP接口也有专用的ifnet结构体存放接口信息。
/****************************************/
/*
 * Definitions for SLIP interface data structures
 *
 * (This exists so programs like slstats can get at the definition
 *  of sl_softc.)
 */
struct sl_softc {
    struct    ifnet sc_if;        /* network-visible interface */
    struct    ifqueue sc_fastq;    /* interactive output queue */
    struct    tty *sc_ttyp;        /* pointer to tty structure */
    u_char    *sc_mp;            /* pointer to next available buf char */
    u_char    *sc_ep;            /* pointer to last available buf char */
    u_char    *sc_buf;        /* input buffer */
    u_int    sc_flags;        /* see below */
    u_int    sc_escape;    /* =1 if last char input was FRAME_ESCAPE */
    long    sc_lasttime;        /* last time a char arrived */
    long    sc_abortcount;        /* number of abort esacpe chars */
    long    sc_starttime;        /* time of first abort in window */
#ifdef INET                /* XXX */
    struct    slcompress sc_comp;    /* tcp compression data */
#endif
    caddr_t    sc_bpf;            /* BPF data */
};
struct sl_softc sl_softc[NSL];
/***************************************/
sc_if 通用的ifnet结构,保存接口共有的信息
结构体的其他信息为SLIP接口特有的信息

NSL 内核配置的支持最大SLIP接口个数。

slattach()函数:
/*******************************************/
void
slattach()
{
    register struct sl_softc *sc;
    register int i = 0;

    for (sc = sl_softc; i < NSL; sc++) {
        sc->sc_if.if_name = "sl";
        sc->sc_if.if_next = NULL;
        sc->sc_if.if_unit = i++;
        sc->sc_if.if_mtu = SLMTU;
        sc->sc_if.if_flags =
            IFF_POINTOPOINT | SC_AUTOCOMP | IFF_MULTICAST;
        sc->sc_if.if_type = IFT_SLIP;
        sc->sc_if.if_ioctl = slioctl;
        sc->sc_if.if_output = sloutput;
        sc->sc_if.if_snd.ifq_maxlen = 50;
        sc->sc_fastq.ifq_maxlen = 32;
        if_attach(&sc->sc_if);
#if NBPFILTER > 0
        bpfattach(&sc->sc_bpf, &sc->sc_if, DLT_SLIP, SLIP_HDRLEN);
#endif
    }
}
/*******************************************/
该函数循环的初始化NSL个SLIP接口,设置接口标记,以及一些接口驱动函数的入口。
之后再通过函数if_attach将接口插入接口链表。

以上是对SLIP接口结构的初始化过程。要使用SLIP接口,除了初始化接口结构外,还需要打开一个tty设备,并发送ioctl命令用SLIP规程代替标准的线路规程。同时tty子系统调用线路规程打开函数(slopen),此函数在一个特定tty设备和一个特定SLIP接口间建立关系。
slopen函数
/********************************************/
/*
 * Line specific open routine.
 * Attach the given tty to the first available sl unit.
 */
/* ARGSUSED */
int
slopen(dev, tp)
    dev_t dev;
    register struct tty *tp;
{
    struct proc *p = curproc;        /* XXX */
    register struct sl_softc *sc;
    register int nsl;
    int error;
    int s;

    if (error = suser(p->p_ucred, &p->p_acflag))    /* 判断是否超级用户 */
        return (error);

    if (tp->t_line == SLIPDISC)     /* 如果不是SLIP线程,直接返回*/
        return (0);

    for (nsl = NSL, sc = sl_softc; --nsl >= 0; sc++)
        if (sc->sc_ttyp == NULL) {  /* 查找一个未使用的项 */
            if (slinit(sc) == 0)   
                return (ENOBUFS);
            tp->t_sc = (caddr_t)sc;
            sc->sc_ttyp = tp;   /* 关联tty和slip线路 */
            sc->sc_if.if_baudrate = tp->t_ospeed;
            s = spltty();
            tp->t_state |= TS_ISOPEN | TS_XCLUDE;   /* 设置tty的状态 */
            splx(s);
            ttyflush(tp, FREAD | FWRITE); /* 丢弃任何tty队列中输入和输出的数据 */
            return (0);
        }
    return (ENXIO);
}
/********************************************/
slinit函数,初始化SLIP接口专用的结构,初始化接收发送缓存
/********************************************/
static int
slinit(sc)
    register struct sl_softc *sc;
{
    register caddr_t p;

    if (sc->sc_ep == (u_char *) 0) {
        MCLALLOC(p, M_WAIT);    /* 分配一个mbuf */
        if (p)
            sc->sc_ep = (u_char *)p + SLBUFSIZE; /* sc_ep指向这个簇的结束 */
        else {  /* 如果分配失败,禁用该接口 */
            printf("sl%d: can't allocate buffer/n", sc - sl_softc);
            sc->sc_if.if_flags &= ~IFF_UP;
            return (0);
        }
    }
    sc->sc_buf = sc->sc_ep - SLMAX;     /* sc_buf 指向簇中分组的起始位置 */
    sc->sc_mp = sc->sc_buf;     /* sc_mp指向要接收的下一个字节的位置 */
    sl_compress_init(&sc->sc_comp);     /* 初始化TCP首部的压缩状态 */
    return (1);
}
/********************************************/
sc_buf并不指向簇的第一个字节,slinit保留148字节(BUFOFFSET)的空间,为输入分组的压缩首部做扩展。

三、SLIP接口的输入处理
tty驱动程序每次调用slinput函数,输入字符传给SLIP线路规程。
slinput函数
/********************************************/
/*
 * tty interface receiver interrupt.
 */
void
slinput(c, tp)
    register int c;     /* 输入的字符 */
    register struct tty *tp; /* tty设备的指针 */
{
    register struct sl_softc *sc;
    register struct mbuf *m;
    register int len;
    int s;
#if NBPFILTER > 0
    u_char chdr[CHDR_LEN];
#endif

    tk_nin++;
    sc = (struct sl_softc *)tp->t_sc;  /* 线程对应的接口 */ 
    if (sc == NULL)
        return;
    if ((c & TTY_ERRORMASK) || ((tp->t_state & TS_CARR_ON) == 0 &&
        (tp->t_cflag & CLOCAL) == 0)) {     /* 丢弃错误的字符 */
        sc->sc_flags |= SC_ERROR;
        return;
    }
    c &= TTY_CHARMASK;  /* 丢弃c中的控制比特*/

    ++sc->sc_if.if_ibytes;  /* 更新接口接收到的字节计数 */

    if (sc->sc_if.if_flags & IFF_DEBUG) {
        if (c == ABT_ESC) {
            /*
             * If we have a previous abort, see whether
             * this one is within the time limit.
             */
            if (sc->sc_abortcount &&
                time.tv_sec >= sc->sc_starttime + ABT_WINDOW)
                sc->sc_abortcount = 0;
            /*
             * If we see an abort after "idle" time, count it;
             * record when the first abort escape arrived.
             */
            if (time.tv_sec >= sc->sc_lasttime + ABT_IDLE) {
                if (++sc->sc_abortcount == 1)
                    sc->sc_starttime = time.tv_sec;
                if (sc->sc_abortcount >= ABT_COUNT) {
                    slclose(tp);
                    return;
                }
            }
        } else
            sc->sc_abortcount = 0;
        sc->sc_lasttime = time.tv_sec;
    }

    switch (c) {

    case TRANS_FRAME_ESCAPE:
        if (sc->sc_escape)
            c = FRAME_ESCAPE;   /* ESC转义字符替换成ESC */
        break;

    case TRANS_FRAME_END:
        if (sc->sc_escape)
            c = FRAME_END;      /* END转义字符替换成END */
        break;

    case FRAME_ESCAPE:
        sc->sc_escape = 1;      /* 记录END,并返回 */
        return;

    case FRAME_END:
        if(sc->sc_flags & SC_ERROR) {   /* 如果是错误,直接丢弃该包 */
            sc->sc_flags &= ~SC_ERROR;
            goto newpack;
        }
        len = sc->sc_mp - sc->sc_buf;   /* 计算包的长度 */
        if (len < 3)    /* 小于3,直接忽略 */
            /* less than min length packet - ignore */
            goto newpack;

#if NBPFILTER > 0
        if (sc->sc_bpf) {   /* 注册了sc_bpf,需要拷贝一份数据 */
            /*
             * Save the compressed header, so we
             * can tack it on later.  Note that we
             * will end up copying garbage in some
             * cases but this is okay.  We remember
             * where the buffer started so we can
             * compute the new header length.
             */
            bcopy(sc->sc_buf, chdr, CHDR_LEN);
        }
#endif

        if ((c = (*sc->sc_buf & 0xf0)) != (IPVERSION << 4)) {   /* 不是IP分组 */
            if (c & 0x80)   /* 压缩TCP分段 */
                c = TYPE_COMPRESSED_TCP;
            else if (c == TYPE_UNCOMPRESSED_TCP)    /* 未压缩TCP分段  */
                *sc->sc_buf &= 0x4f; /* XXX */
            /*
             * We've got something that's not an IP packet.
             * If compression is enabled, try to decompress it.
             * Otherwise, if `auto-enable' compression is on and
             * it's a reasonable packet, decompress it and then
             * enable compression.  Otherwise, drop it.
             */
            if (sc->sc_if.if_flags & SC_COMPRESS) {     /* 分组允许压缩,sl_uncompress_tcp解压缩 */
                len = sl_uncompress_tcp(&sc->sc_buf, len,
                            (u_int)c, &sc->sc_comp);
                if (len <= 0)
                    goto error;
            } else if ((sc->sc_if.if_flags & SC_AUTOCOMP) &&
                c == TYPE_UNCOMPRESSED_TCP && len >= 40) { /* 设置了自动允许压缩,并且分组足够大,仍然调用解压缩 */
                len = sl_uncompress_tcp(&sc->sc_buf, len,
                            (u_int)c, &sc->sc_comp);
                if (len <= 0)
                    goto error;
                sc->sc_if.if_flags |= SC_COMPRESS; /* 设置允许压缩标志 */
            } else
                goto error;
        }
#if NBPFILTER > 0
        if (sc->sc_bpf) {
            /*
             * Put the SLIP pseudo-"link header" in place.
             * We couldn't do this any earlier since
             * decompression probably moved the buffer
             * pointer.  Then, invoke BPF.
             */
            register u_char *hp = sc->sc_buf - SLIP_HDRLEN;

            hp[SLX_DIR] = SLIPDIR_IN;   /* 标记分组的方向为输入 */
            bcopy(chdr, &hp[SLX_CHDR], CHDR_LEN);   /* 拷贝压缩的首部 */
            bpf_tap(sc->sc_bpf, hp, len + SLIP_HDRLEN); /*  将首部和分组传给bpf */
        }
#endif
        m = sl_btom(sc, len);   /* 将簇转换为一个mbuf链表 */
        if (m == NULL)
            goto error;

        sc->sc_if.if_ipackets++;    /* 更新统计 */
        sc->sc_if.if_lastchange = time;
        s = splimp();   /* 将分组放入ipintrq队列 */
        if (IF_QFULL(&ipintrq)) {
            IF_DROP(&ipintrq);
            sc->sc_if.if_ierrors++;
            sc->sc_if.if_iqdrops++;
            m_freem(m);
        } else {
            IF_ENQUEUE(&ipintrq, m);
            schednetisr(NETISR_IP);
        }
        splx(s);
        goto newpack;
    }
    if (sc->sc_mp < sc->sc_ep) {    /* 将输入的字符放入簇中 */
        *sc->sc_mp++ = c;
        sc->sc_escape = 0;  /* 清除接收到ESC的标志 */
        return;
    }

    /* can't put lower; would miss an extra frame */
    sc->sc_flags |= SC_ERROR;

error:
    sc->sc_if.if_ierrors++;
newpack: /* 开始接收新的分组,清除记录 */
    sc->sc_mp = sc->sc_buf = sc->sc_ep - SLMAX;
    sc->sc_escape = 0;
}
/********************************************/

四、SLIP接口的输出处理
sloutput函数
当一个网络层协议调用接口的if_output(sloutput)函数时,开始处理输出。
/*******************************************/
/*
 * Queue a packet.  Start transmission if not active.
 * Compression happens in slstart; if we do it here, IP TOS
 * will cause us to not compress "background" packets, because
 * ordering gets trashed.  It can be done for all packets in slstart.
 */
int
sloutput(ifp, m, dst, rtp)
    struct ifnet *ifp;
    register struct mbuf *m;
    struct sockaddr *dst;
    struct rtentry *rtp;
{
    register struct sl_softc *sc = &sl_softc[ifp->if_unit];
    register struct ip *ip;
    register struct ifqueue *ifq;
    int s;

    /*
     * `Cannot happen' (see slioctl).  Someday we will extend
     * the line protocol to support other address families.
     */
    if (dst->sa_family != AF_INET) {    /* 目标地址是否IP地址 */
        printf("sl%d: af%d not supported/n", sc->sc_if.if_unit,
            dst->sa_family);
        m_freem(m);
        sc->sc_if.if_noproto++;
        return (EAFNOSUPPORT);
    }

    if (sc->sc_ttyp == NULL) {          /* 是否打开了tty */
        m_freem(m);
        return (ENETDOWN);    /* sort of */
    }
    if ((sc->sc_ttyp->t_state & TS_CARR_ON) == 0 &&
        (sc->sc_ttyp->t_cflag & CLOCAL) == 0) {     /* 接口是否正在运行 */
        m_freem(m);
        return (EHOSTUNREACH);
    }
    ifq = &sc->sc_if.if_snd;
    ip = mtod(m, struct ip *);
    if (sc->sc_if.if_flags & SC_NOICMP && ip->ip_p == IPPROTO_ICMP) { /* 如果接口被设置为SC_NOICMP且分组是ICMP则丢弃 */
        m_freem(m);
        return (ENETRESET);        /* XXX ? */
    }
    if (ip->ip_tos & IPTOS_LOWDELAY)    /* 如果输出的分组TOS字段指明为低时延服务,输出队列改为sc_fastq */
        ifq = &sc->sc_fastq;
    s = splimp();
    if (IF_QFULL(ifq)) {
        IF_DROP(ifq);
        m_freem(m);
        splx(s);
        sc->sc_if.if_oerrors++;
        return (ENOBUFS);
    }
    IF_ENQUEUE(ifq, m);
    sc->sc_if.if_lastchange = time;
    if (sc->sc_ttyp->t_outq.c_cc == 0) /* 如果tty的输出队列是空的,调用slstart往tty队列送数据 */
        slstart(sc->sc_ttyp);
    splx(s);
    return (0);
}
/*******************************************/
sloutput说明了SLIP接口在接口层对输出数据的处理。
其中的slstart函数用于往tty设备写入输出的数据。
tty子系统通过一个clist结构管理它的队列,如果输出队列t_outq不为空,
slstart调用设备的输出函数t_oproc,当队列的剩余字节数超过一定值,slstart返回。
如果tty的队列为空,从sc_fastq中退队一个分组,或者若sc_fastq为空,则从if_snd队列退队一个分组。

slstart()函数
/*******************************************/
/*
 * Start output on interface.  Get another datagram
 * to send from the interface queue and map it to
 * the interface before starting output.
 */
void
slstart(tp)
    register struct tty *tp;
{
    register struct sl_softc *sc = (struct sl_softc *)tp->t_sc;
    register struct mbuf *m;
    register u_char *cp;
    register struct ip *ip;
    int s;
    struct mbuf *m2;
#if NBPFILTER > 0
    u_char bpfbuf[SLMTU + SLIP_HDRLEN];
    register int len;
#endif
    extern int cfreecount;

    for (;;) {
        /*
         * If there is more in the output queue, just send it now.
         * We are being called in lieu of ttstart and must do what
         * it would.
         */
        if (tp->t_outq.c_cc != 0) {
            (*tp->t_oproc)(tp);
            if (tp->t_outq.c_cc > SLIP_HIWAT)
                return;
        }
        /*
         * This happens briefly when the line shuts down.
         */
        if (sc == NULL)
            return;

        /*
         * Get a packet and send it to the interface.
         */
        //从sc_fastq队列退队或从if_snd队列退队
        s = splimp();
        IF_DEQUEUE(&sc->sc_fastq, m);
        if (m)
            sc->sc_if.if_omcasts++;        /* XXX */
        else
            IF_DEQUEUE(&sc->sc_if.if_snd, m);
        splx(s);
        if (m == NULL)
            return;

        /*
         * We do the header compression here rather than in sloutput
         * because the packets will be out of order if we are using TOS
         * queueing, and the connection id compression will get
         * munged when this happens.
         */
#if NBPFILTER > 0
        if (sc->sc_bpf) {
            /*
             * We need to save the TCP/IP header before it's
             * compressed.  To avoid complicated code, we just
             * copy the entire packet into a stack buffer (since
             * this is a serial line, packets should be short
             * and/or the copy should be negligible cost compared
             * to the packet transmission time).
             */
            register struct mbuf *m1 = m;
            register u_char *cp = bpfbuf + SLIP_HDRLEN;

            len = 0;
            do {
                register int mlen = m1->m_len;

                bcopy(mtod(m1, caddr_t), cp, mlen);
                cp += mlen;
                len += mlen;
            } while (m1 = m1->m_next);
        }
#endif
        //压缩TCP首部
        if ((ip = mtod(m, struct ip *))->ip_p == IPPROTO_TCP) {
            if (sc->sc_if.if_flags & SC_COMPRESS)
                *mtod(m, u_char *) |= sl_compress_tcp(m, ip,
                    &sc->sc_comp, 1);
        }
#if NBPFILTER > 0
        //分组数据送到bpf_tap
        if (sc->sc_bpf) {
            /*
             * Put the SLIP pseudo-"link header" in place.  The
             * compressed header is now at the beginning of the
             * mbuf.
             */
            bpfbuf[SLX_DIR] = SLIPDIR_OUT;
            bcopy(mtod(m, caddr_t), &bpfbuf[SLX_CHDR], CHDR_LEN);
            bpf_tap(sc->sc_bpf, bpfbuf, len + SLIP_HDRLEN);
        }
#endif
        sc->sc_if.if_lastchange = time;

        /*
         * If system is getting low on clists, just flush our
         * output queue (if the stuff was important, it'll get
         * retransmitted).
         */
        if (cfreecount < CLISTRESERVE + SLMTU) {
            m_freem(m);
            sc->sc_if.if_collisions++;
            continue;
        }
        /*
         * The extra FRAME_END will start up a new packet, and thus
         * will flush any accumulated garbage.  We do this whenever
         * the line may have been idle for some time.
         */
        //当SLIP线为空时,往t_outq队列输出FRAME_END
        if (tp->t_outq.c_cc == 0) {
            ++sc->sc_if.if_obytes;
            (void) putc(FRAME_END, &tp->t_outq);
        }

        while (m) {
            register u_char *ep;

            cp = mtod(m, u_char *); ep = cp + m->m_len;
            while (cp < ep) {
                /*
                 * Find out how many bytes in the string we can
                 * handle without doing something special.
                 */
                //发送特殊字符外的其他字符
                register u_char *bp = cp;

                while (cp < ep) {
                    switch (*cp++) {
                    case FRAME_ESCAPE:
                    case FRAME_END:
                        --cp;
                        goto out;
                    }
                }
                out:
                if (cp > bp) {
                    /*
                     * Put n characters at once
                     * into the tty output queue.
                     */
                    if (b_to_q((char *)bp, cp - bp,
                        &tp->t_outq))
                        break;
                    sc->sc_if.if_obytes += cp - bp;
                }
                /*
                 * If there are characters left in the mbuf,
                 * the first one must be special..
                 * Put it out in a different form.
                 */
                //发送特殊字符
                if (cp < ep) {
                    if (putc(FRAME_ESCAPE, &tp->t_outq))
                        break;
                    if (putc(*cp++ == FRAME_ESCAPE ?
                       TRANS_FRAME_ESCAPE : TRANS_FRAME_END,
                       &tp->t_outq)) {
                        (void) unputc(&tp->t_outq);
                        break;
                    }
                    sc->sc_if.if_obytes += 2;
                }
            }
            MFREE(m, m2);
            m = m2;
        }

        //发送帧结束字符
        if (putc(FRAME_END, &tp->t_outq)) {
            /*
             * Not enough room.  Remove a char to make room
             * and end the packet normally.
             * If you get many collisions (more than one or two
             * a day) you probably do not have enough clists
             * and you should increase "nclist" in param.c.
             */
            (void) unputc(&tp->t_outq);
            (void) putc(FRAME_END, &tp->t_outq);
            sc->sc_if.if_collisions++;
        } else {
            ++sc->sc_if.if_obytes;
            sc->sc_if.if_opackets++;
        }
    }
}
/*************************************************************/
该函数的函数体内部是个大的循环,从数据输出队列退队分组,并组成SLIP帧。

五、SLIP的性能考虑
(1)小的MTU值能改善交互数据的延迟,但会降低批量数据的吞吐量。
大的MTU能改进批量数据的吞吐量,但会增加交互时延。
如果为交互比较频繁的应用提供服务,可以采用一个足够大的MTU满足交互响应时间和吞吐率的要求。
如果在SLIP上传输TCP/IP分组,采用压缩TCP/IP首部来减少每个分组的负荷。
(2)SLIP_HIWAT的大小会影响到slstart调用的频率。
如果值太大,会有比较多的数据在缓存中,新的交互数据不能及时的发送。如果值太小,会比较频繁的调用slstart函数。
(3)SLIP驱动程序提供了TOS排队。
其策略是先从sc_fastq队列中发送交互数据,然后在标准接口队列if_snd中发送其他的通信数据

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/mythfish/archive/2008/11/23/3356799.aspx

SLIP 多模态 文本图像对比学与图像图像对比学习结合 参考:https://github.com/facebookresearch/SLIP 原理:相当于结合clip和simclr两个对比学习的损失,等于文本图像对比学与图像图像对比学习结合 1、离线图像或者文本计算保存 需要先下载预训练好的模型:https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt from torchvision import transforms import torch from PIL import Image import 阅读详情

相关推荐

C++的slip协议帧报文程序

C++的slip协议帧报文程序,串口转网络协议,串口转网络协议

linux系统调用

概述 本文学习基于armv7和armv8体系的linux系统调用机制,linux内核版本为3.10.79。通过分析系统调用机制和源代码来展示系统调用过程。 什么是系统调用 linux内核中设置了一组用于实现系统功能的子程序,称为系统调用。系统调用和普通库函数调用很相似,仅仅是系统调用由操作系统核心提供,执行于核心态。而普通的函数调用由函数库或用户自己提供。执行于用户态。 通常系统调用过程如...

osnet的博客 724

SLIP协议程序代码SLIP_v1.cpp

已经在vxworks上成功进行了编解码测试。编解码比较简单,已经封装好了编码函数和解码函数。大家可以稍加修改移植到你自己的平台。

SLIP驱动程序 C语言实现

SLIP驱动程序下面的C语言函数发送并接收SLIP分组。它们依赖于send_char() 和 recv_char(),这两个函数在串行线路上发送和接收单个字符。/* SLIP 特殊字符编码 */#define END 0300 /* 分组结束标记 */#define ESC 0333 /* 填充字节标记*/#define ESC_END 0334 /* ESC ESC_END 表示数据

奇幻风云 4872

当勒索软件盯上虚拟化层:从CVE-2025-22225漏洞看ESXi安全加固要点

本文深度剖析了针对VMware ESXi虚拟化层的CVE-2025-22225等漏洞链的攻击原理,揭示了攻击者如何利用VMCI、HGFS组件从虚拟机逃逸至宿主机。文章从实战角度出发,系统性地提出了ESXi安全加固的核心策略,包括禁用非必要服务、强化主机配置、实施网络分段、建立实时监控与自动化补丁管理体系,为企业构建纵深防御体系提供了具体可行的操作指南。

terraform7cloud的博客 875

uniCloud云存储进阶:七牛云扩展存储从开通、绑定域名到批量上传的完整实战

本文详细介绍了uniCloud云存储进阶实践,重点讲解如何通过七牛云扩展存储实现从开通、绑定域名到批量上传的完整流程。内容涵盖成本优势分析、域名备案方案、SSL证书配置、多文件并发上传控制等实战技巧,并提供可直接复用的代码示例,帮助开发者高效构建内容社区类应用。

weixin_26985923的博客 473

slip协议的实现 c语言,SLIP驱动程序 C语言实现

SLIP驱动程序下面的C语言函数发送并接收SLIP分组。它们依赖于send_char() 和 recv_char(),这两个函数在串行线路上发送和接收单个字符。/* SLIP 特殊字符编码 */#define END 0300 /* 分组结束标记 */#define ESC 0333 /* 填充字节标记*/#define ESC_END 0334 /* ESC ESC_END 表示数据字节END ...

weixin_39937447的博客 1504

博图V16与840D sl数控系统PLC编程实战指南

本文为西门子840D sl数控系统的PLC编程实战指南,详细介绍了如何使用博图V16软件配置编程环境。内容涵盖从项目创建、核心程序块(如DB、FB)解析到OB1主循环编程的完整流程,并提供了高级调试技巧与联调避坑指南,帮助工程师快速上手并高效完成系统集成与逻辑控制。

weixin_29193259的博客 529

系统调用的返回值

系统调用(在Linux中常称作syscalls)通常通过函数进行调用。它们通常都需要定义一个或几个参数(输入)而且可能产生一些副作用,例如写某个文件或向给定的指针拷贝数据等等。为防止和正常的返回值混淆,系统调用并不直接返回错误码,而是将错误码放入一个名为errno的全局变量中。通常用一个负的返回值来表明错误。返回一个0值通常表明成功。如果一个系统调用失败,你可以读出errno的值来确定问题所在。通过调用perror()库函数,可以把该变量翻译成用户可以理解的错误字符串。 errno不同数值所代表的错误消息

地推 2067

echarts实现3D地图——map3D

【代码】echarts实现3D地图——map3D。

xiaoququ的博客 7340

OpenFeign整合Sentinel实现熔断降级

常用于实现熔断降级的框架有Hystrix、Sentinel,我们常说的Spring Cloud项目说的其实是Spring Cloud Netflix,Hystrix以及前面学习过的Ribbon都是Netflix系的家族成员,所以使用Hystrix可以非常简单的与当前项目中使用到的OpenFeign、Ribbon整合,但笔者并没有选择Hystrix,而是选择阿里系的Sentinel。 为什么选择Sentinel而不是Hystrix?从接入简单考虑可能选择Hystrix是不错的选择,但笔者对Hyst...

吴就业 6723

《TCP/IP详解卷2:实现》笔记--中断级别与并发

网络代码处理输入分组用的是异步和中断驱动的方式。首先,一个设备中断引发接口层代码执行,然后它产生一个软中断 引发协议层代码执行。当内核完成这些级别的中断后,执行插口代码。当内核完成这些级别的中断后,执行插口代码。 在这里给每个硬件和软件中断分配一个优先级。如下图: 对于不同优先级,一个要关心的问题就是如何处理那些在不同级别的进程共享的数据结构。例如,当IP输入例程正在从它的 输入队

TODD911的专栏 3346

巡检机器人的基于ROS系统的任务管理架构设计总结

本文探讨了基于ROS(机器人操作系统)的工业巡检机器人任务管理架构设计,提出分层闭环方案。架构围绕稳、准、活、扩四大目标,分为感知层(多源数据融合)、调度层(智能决策)、执行层(动作控制)和数据层(存储交互)。关键技术包括ROS2实时性优化、功能包复用和多机器人协同调度。实践案例显示,该架构在电力巡检中使任务完成率达99%,在化工园区实现95%覆盖率。当前挑战包括SLAM地图漂移和多机通信延迟,未来可通过语义SLAM和区域通信优化。

start_up_go的博客 501

linux 系统调用号

linux 系统调用 syscall

yuzyong的博客 1953

Python爬虫实战:逆向分析+异步技术高效抓取微信公众号文章

逆向突破:解析公众号核心接口参数,破解登录态与加密规则;高性能:异步协程+连接池,单进程日均抓取1000+篇文章;高稳定性:自动刷新登录态、IP代理轮换,无人工干预持续运行;高完整性:覆盖文章全量字段,清洗后可直接用于数据分析。接入消息队列(Kafka),实现分布式多公众号并行爬取;增加文章配图下载模块,完整存档多媒体内容;接入Elasticsearch,实现文章全文检索与关键词分析。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 3269

RK3576 PCIE接口调试:基于RTL8111HS的网卡驱动移植

检查项方法电源电压复位时序检查设备树 reset-gpios链路速率设备识别lspci -vvv驱动加载。

小灰灰的博客 762

概说《TCP/IP详解 卷2》第1章 概述

原文链接:https://mp.weixin.qq.com/s/U9lmkrTbagpuKH-4bJcwTg 本文要点 《TCP/IP详解 卷2》原书章节简介 第一个网络编程示例 网络层次结构 描述符 mbuf 网络输出与输入 中断与并发 源码组织结构 《TCP/IP详解 卷2》原书章节简介     原书共32个章...

记录技术成长之路 812

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

lwip 移植

一、源码目录结构        api 、 core、netif、 include       core下又有IPV4 、 IPV6 、 SNMP 和.c文件       include下又有IPV4、IPV6、LWIP、netif       netif下的文件有       1. ethernetif.c这里主要涉及到具体的硬件       2.etharp.c 这里有个函数eth

xxu0123456789的专栏 9532

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

SLIP协议完全指南:从协议原理到嵌入式实战

SLIP的全称是Serial Line IP,它是一种在串行线路上对IP数据报进行封装的简单形式,适用于RS-232串行端口和调制解调器接入Internet。SLIP本质上只是一个“包组帧协议”,仅仅定义了在串行线路上将数据包封装成帧的一系列字符。它没有提供寻址、包类型标识、错误检查/修正或者压缩机制。SLIP通常专门用于串行连接,使用的线路速率一般介于1200bps和19.2Kbps之间,允许主机和路由器混合连接通信(主机-主机、主机-路由器、路由器-路由器都是SLIP网络通用的配置)。

reallin_yzh的博客 732

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

TCPIP协议卷2之io中断

一、操作系统关于网络部分的分层处理 操作系统完成用户和物理链路之间的转换,这种转换可简单分为三个层面,如下图所示: 插口层,直接对应用户的系统调用,完成用户调用参数校验等等,它不设计任何网络协议相关的工作; 协议层,完成协议相关的操作,例如将插口层交过来的数据加上tcp/udp和ip层的头部等等。 网络接口层,完成与物理传输媒介的交互,它包括数据链路层和网卡驱动,它一端对接协议层,一端对接

逍遥子曰: 2158

《TCP-IP详解 卷2:实现》学习笔记—接口层分析

所谓接口,就是指在一个特定网络上硬件与设备驱动器之间的接口。BSD设计将网络协议和连接到一个系统的网络设备的驱动器间提供一个与硬件无关的编程接口。 1、ifnet结构 结构ifnet中包含所有接口的通用信息。在系统初始化期间,分别为每个网络设备分配一个独立的ifnet结构。每个ifnet结构有一个列表,它包含这个设备的一个或多个协议地址。函数if_attach在系统初始化期间构造这个链表。if_addrlist指向这个接口的ifaddr结构列表。每个ifaddr结构存储一个要用这个接口通信的协议的地址信

假装在纽约 2797

驱动函数 c语言,SLIP驱动程序 C语言实现

SLIP驱动程序下面的C语言函数发送并接收SLIP分组。它们依赖于send_char() 和 recv_char(),这两个函数在串行线路上发送和接收单个字符。/* SLIP 特殊字符编码 */#define END 0300 /* 分组结束标记 */#define ESC 0333 /* 填充字节标记*/#define ESC_END 0334 /* ESC ESC_END 表示数据字节END ...

weixin_29363945的博客 403

BSD net源码分析(2-2)

 二、以太网接口接收数据帧    当接口接收到发送给该接口的单播地址和广播地址的帧,帧可用时,触发一个中断,并且内核调用驱动函数函数leintr()。    leintr()函数内部根据硬件寄存器的值,判断是什么中断,如果是LE_RINT状态,调用lerint处理接收的数据,如果是LE_TINT,调用lexint做输出数据处理。    其他的状态,程序会更新接口的统计,并调用lereset重设接口

技术爬虫(tech-reptile) 1098
上一篇: 手机开发平台指南、教程和资料介绍
下一篇: BSD net源码分析(4)──环回接口
流水时间
博客等级 码龄19年 23粉丝 30原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值