]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/xen/netfront/netfront.c
Merge OpenBSM 1.1 alpha 2 from the OpenBSM vendor branch to head, both
[FreeBSD/FreeBSD.git] / sys / dev / xen / netfront / netfront.c
1 /*
2  *
3  * Copyright (c) 2004-2006 Kip Macy
4  * All rights reserved.
5  *
6  *
7  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
8  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
9  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
10  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
11  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
12  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
13  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
14  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
16  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17  */
18
19
20 #include <sys/cdefs.h>
21 __FBSDID("$FreeBSD$");
22
23 #include <sys/param.h>
24 #include <sys/systm.h>
25 #include <sys/sockio.h>
26 #include <sys/mbuf.h>
27 #include <sys/malloc.h>
28 #include <sys/kernel.h>
29 #include <sys/socket.h>
30 #include <sys/queue.h>
31 #include <sys/sx.h>
32
33 #include <net/if.h>
34 #include <net/if_arp.h>
35 #include <net/ethernet.h>
36 #include <net/if_dl.h>
37 #include <net/if_media.h>
38
39 #include <net/bpf.h>
40
41 #include <net/if_types.h>
42 #include <net/if.h>
43
44 #include <netinet/in_systm.h>
45 #include <netinet/in.h>
46 #include <netinet/ip.h>
47 #include <netinet/if_ether.h>
48
49 #include <vm/vm.h>
50 #include <vm/pmap.h>
51
52 #include <machine/clock.h>      /* for DELAY */
53 #include <machine/bus.h>
54 #include <machine/resource.h>
55 #include <machine/frame.h>
56 #include <machine/vmparam.h>
57
58 #include <sys/bus.h>
59 #include <sys/rman.h>
60
61 #include <machine/intr_machdep.h>
62
63 #include <machine/xen/xen-os.h>
64 #include <machine/xen/hypervisor.h>
65 #include <machine/xen/xen_intr.h>
66 #include <machine/xen/evtchn.h>
67 #include <machine/xen/xenbus.h>
68 #include <xen/gnttab.h>
69 #include <xen/interface/memory.h>
70 #include <dev/xen/netfront/mbufq.h>
71 #include <machine/xen/features.h>
72 #include <xen/interface/io/netif.h>
73
74
75 #define GRANT_INVALID_REF       0
76
77 #define NET_TX_RING_SIZE __RING_SIZE((netif_tx_sring_t *)0, PAGE_SIZE)
78 #define NET_RX_RING_SIZE __RING_SIZE((netif_rx_sring_t *)0, PAGE_SIZE)
79
80 #ifdef CONFIG_XEN
81 static int MODPARM_rx_copy = 0;
82 module_param_named(rx_copy, MODPARM_rx_copy, bool, 0);
83 MODULE_PARM_DESC(rx_copy, "Copy packets from network card (rather than flip)");
84 static int MODPARM_rx_flip = 0;
85 module_param_named(rx_flip, MODPARM_rx_flip, bool, 0);
86 MODULE_PARM_DESC(rx_flip, "Flip packets from network card (rather than copy)");
87 #else
88 static const int MODPARM_rx_copy = 1;
89 static const int MODPARM_rx_flip = 0;
90 #endif
91
92 #define RX_COPY_THRESHOLD 256
93
94 #define net_ratelimit() 0
95
96 struct netfront_info;
97 struct netfront_rx_info;
98
99 static void xn_txeof(struct netfront_info *);
100 static void xn_rxeof(struct netfront_info *);
101 static void network_alloc_rx_buffers(struct netfront_info *);
102
103 static void xn_tick_locked(struct netfront_info *);
104 static void xn_tick(void *);
105
106 static void xn_intr(void *);
107 static void xn_start_locked(struct ifnet *);
108 static void xn_start(struct ifnet *);
109 static int  xn_ioctl(struct ifnet *, u_long, caddr_t);
110 static void xn_ifinit_locked(struct netfront_info *);
111 static void xn_ifinit(void *);
112 static void xn_stop(struct netfront_info *);
113 #ifdef notyet
114 static void xn_watchdog(struct ifnet *);
115 #endif
116
117 static void show_device(struct netfront_info *sc);
118 #ifdef notyet
119 static void netfront_closing(struct xenbus_device *dev);
120 #endif
121 static void netif_free(struct netfront_info *info);
122 static int netfront_remove(struct xenbus_device *dev);
123
124 static int talk_to_backend(struct xenbus_device *dev, struct netfront_info *info);
125 static int create_netdev(struct xenbus_device *dev, struct ifnet **ifp);
126 static void netif_disconnect_backend(struct netfront_info *info);
127 static int setup_device(struct xenbus_device *dev, struct netfront_info *info);
128 static void end_access(int ref, void *page);
129
130 /* Xenolinux helper functions */
131 static int network_connect(struct ifnet *ifp);
132
133 static void xn_free_rx_ring(struct netfront_info *);
134
135 static void xn_free_tx_ring(struct netfront_info *);
136
137 static int xennet_get_responses(struct netfront_info *np,
138         struct netfront_rx_info *rinfo, RING_IDX rp, struct mbuf **list,
139         int *pages_flipped_p);
140
141 #define virt_to_mfn(x) (vtomach(x) >> PAGE_SHIFT)
142
143 #define INVALID_P2M_ENTRY (~0UL)
144
145 /*
146  * Mbuf pointers. We need these to keep track of the virtual addresses
147  * of our mbuf chains since we can only convert from virtual to physical,
148  * not the other way around.  The size must track the free index arrays.
149  */
150 struct xn_chain_data {
151                 struct mbuf             *xn_tx_chain[NET_TX_RING_SIZE+1];
152                 struct mbuf             *xn_rx_chain[NET_RX_RING_SIZE+1];
153 };
154
155
156 struct net_device_stats
157 {
158         u_long  rx_packets;             /* total packets received       */
159         u_long  tx_packets;             /* total packets transmitted    */
160         u_long  rx_bytes;               /* total bytes received         */
161         u_long  tx_bytes;               /* total bytes transmitted      */
162         u_long  rx_errors;              /* bad packets received         */
163         u_long  tx_errors;              /* packet transmit problems     */
164         u_long  rx_dropped;             /* no space in linux buffers    */
165         u_long  tx_dropped;             /* no space available in linux  */
166         u_long  multicast;              /* multicast packets received   */
167         u_long  collisions;
168
169         /* detailed rx_errors: */
170         u_long  rx_length_errors;
171         u_long  rx_over_errors;         /* receiver ring buff overflow  */
172         u_long  rx_crc_errors;          /* recved pkt with crc error    */
173         u_long  rx_frame_errors;        /* recv'd frame alignment error */
174         u_long  rx_fifo_errors;         /* recv'r fifo overrun          */
175         u_long  rx_missed_errors;       /* receiver missed packet       */
176
177         /* detailed tx_errors */
178         u_long  tx_aborted_errors;
179         u_long  tx_carrier_errors;
180         u_long  tx_fifo_errors;
181         u_long  tx_heartbeat_errors;
182         u_long  tx_window_errors;
183         
184         /* for cslip etc */
185         u_long  rx_compressed;
186         u_long  tx_compressed;
187 };
188
189 struct netfront_info {
190                 
191         struct ifnet *xn_ifp;
192
193         struct net_device_stats stats;
194         u_int tx_full;
195
196         netif_tx_front_ring_t tx;
197         netif_rx_front_ring_t rx;
198
199         struct mtx   tx_lock;
200         struct mtx   rx_lock;
201         struct sx    sc_lock;
202
203         u_int handle;
204         u_int irq;
205         u_int copying_receiver;
206         u_int carrier;
207                 
208         /* Receive-ring batched refills. */
209 #define RX_MIN_TARGET 32
210 #define RX_MAX_TARGET NET_RX_RING_SIZE
211         int rx_min_target, rx_max_target, rx_target;
212
213         /*
214          * {tx,rx}_skbs store outstanding skbuffs. The first entry in each
215          * array is an index into a chain of free entries.
216          */
217
218         grant_ref_t gref_tx_head;
219         grant_ref_t grant_tx_ref[NET_TX_RING_SIZE + 1]; 
220         grant_ref_t gref_rx_head;
221         grant_ref_t grant_rx_ref[NET_TX_RING_SIZE + 1]; 
222
223 #define TX_MAX_TARGET min(NET_RX_RING_SIZE, 256)
224         struct xenbus_device *xbdev;
225         int tx_ring_ref;
226         int rx_ring_ref;
227         uint8_t mac[ETHER_ADDR_LEN];
228         struct xn_chain_data    xn_cdata;       /* mbufs */
229         struct mbuf_head xn_rx_batch;   /* head of the batch queue */
230
231         int                     xn_if_flags;
232         struct callout          xn_stat_ch;
233
234         u_long rx_pfn_array[NET_RX_RING_SIZE];
235         multicall_entry_t rx_mcl[NET_RX_RING_SIZE+1];
236         mmu_update_t rx_mmu[NET_RX_RING_SIZE];
237 };
238
239 #define rx_mbufs xn_cdata.xn_rx_chain
240 #define tx_mbufs xn_cdata.xn_tx_chain
241
242 #define XN_LOCK_INIT(_sc, _name) \
243         mtx_init(&(_sc)->tx_lock, #_name"_tx", "network transmit lock", MTX_DEF); \
244         mtx_init(&(_sc)->rx_lock, #_name"_rx", "network receive lock", MTX_DEF);  \
245         sx_init(&(_sc)->sc_lock, #_name"_rx")
246
247 #define XN_RX_LOCK(_sc)           mtx_lock(&(_sc)->rx_lock)
248 #define XN_RX_UNLOCK(_sc)         mtx_unlock(&(_sc)->rx_lock)
249
250 #define XN_TX_LOCK(_sc)           mtx_lock(&(_sc)->tx_lock)
251 #define XN_TX_UNLOCK(_sc)         mtx_unlock(&(_sc)->tx_lock)
252
253 #define XN_LOCK(_sc)           sx_xlock(&(_sc)->sc_lock); 
254 #define XN_UNLOCK(_sc)         sx_xunlock(&(_sc)->sc_lock); 
255
256 #define XN_LOCK_ASSERT(_sc)    sx_assert(&(_sc)->sc_lock, SX_LOCKED); 
257 #define XN_RX_LOCK_ASSERT(_sc)    mtx_assert(&(_sc)->rx_lock, MA_OWNED); 
258 #define XN_TX_LOCK_ASSERT(_sc)    mtx_assert(&(_sc)->tx_lock, MA_OWNED); 
259 #define XN_LOCK_DESTROY(_sc)   mtx_destroy(&(_sc)->rx_lock); \
260                                mtx_destroy(&(_sc)->tx_lock); \
261                                sx_destroy(&(_sc)->sc_lock);
262
263 struct netfront_rx_info {
264         struct netif_rx_response rx;
265         struct netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX - 1];
266 };
267
268 #define netfront_carrier_on(netif)      ((netif)->carrier = 1)
269 #define netfront_carrier_off(netif)     ((netif)->carrier = 0)
270 #define netfront_carrier_ok(netif)      ((netif)->carrier)
271
272 /* Access macros for acquiring freeing slots in xn_free_{tx,rx}_idxs[]. */
273
274
275
276 /*
277  * Access macros for acquiring freeing slots in tx_skbs[].
278  */
279
280 static inline void
281 add_id_to_freelist(struct mbuf **list, unsigned short id)
282 {
283         list[id] = list[0];
284         list[0]  = (void *)(u_long)id;
285 }
286
287 static inline unsigned short
288 get_id_from_freelist(struct mbuf **list)
289 {
290         u_int id = (u_int)(u_long)list[0];
291         list[0] = list[id];
292         return (id);
293 }
294
295 static inline int
296 xennet_rxidx(RING_IDX idx)
297 {
298         return idx & (NET_RX_RING_SIZE - 1);
299 }
300
301 static inline struct mbuf *
302 xennet_get_rx_mbuf(struct netfront_info *np,
303                                                 RING_IDX ri)
304 {
305         int i = xennet_rxidx(ri);
306         struct mbuf *m;
307
308         m = np->rx_mbufs[i];
309         np->rx_mbufs[i] = NULL;
310         return (m);
311 }
312
313 static inline grant_ref_t
314 xennet_get_rx_ref(struct netfront_info *np, RING_IDX ri)
315 {
316         int i = xennet_rxidx(ri);
317         grant_ref_t ref = np->grant_rx_ref[i];
318         np->grant_rx_ref[i] = GRANT_INVALID_REF;
319         return ref;
320 }
321
322 #ifdef DEBUG
323
324 #endif
325 #define IPRINTK(fmt, args...) \
326     printf("[XEN] " fmt, ##args)
327 #define WPRINTK(fmt, args...) \
328     printf("[XEN] " fmt, ##args)
329 #define DPRINTK(fmt, args...) \
330     printf("[XEN] " fmt, ##args)
331
332
333 static __inline struct mbuf* 
334 makembuf (struct mbuf *buf)
335 {
336         struct mbuf *m = NULL;
337         
338         MGETHDR (m, M_DONTWAIT, MT_DATA);
339         
340         if (! m)
341                 return 0;
342                 
343                 M_MOVE_PKTHDR(m, buf);
344
345                 m_cljget(m, M_DONTWAIT, MJUMPAGESIZE);
346         m->m_pkthdr.len = buf->m_pkthdr.len;
347         m->m_len = buf->m_len;
348                 m_copydata(buf, 0, buf->m_pkthdr.len, mtod(m,caddr_t) );
349
350                 m->m_ext.ext_arg1 = (caddr_t *)(uintptr_t)(vtophys(mtod(m,caddr_t)) >> PAGE_SHIFT);
351         
352         return m;
353 }
354
355 /**
356  * Read the 'mac' node at the given device's node in the store, and parse that
357  * as colon-separated octets, placing result the given mac array.  mac must be
358  * a preallocated array of length ETH_ALEN (as declared in linux/if_ether.h).
359  * Return 0 on success, or errno on error.
360  */
361 static int 
362 xen_net_read_mac(struct xenbus_device *dev, uint8_t mac[])
363 {
364         char *s;
365         int i;
366         char *e;
367         char *macstr = xenbus_read(XBT_NIL, dev->nodename, "mac", NULL);
368         if (IS_ERR(macstr)) {
369                 return PTR_ERR(macstr);
370         }
371         s = macstr;
372         for (i = 0; i < ETHER_ADDR_LEN; i++) {
373                 mac[i] = strtoul(s, &e, 16);
374                 if (s == e || (e[0] != ':' && e[0] != 0)) {
375                         free(macstr, M_DEVBUF);
376                         return ENOENT;
377                 }
378                 s = &e[1];
379         }
380         free(macstr, M_DEVBUF);
381         return 0;
382 }
383
384 /**
385  * Entry point to this code when a new device is created.  Allocate the basic
386  * structures and the ring buffers for communication with the backend, and
387  * inform the backend of the appropriate details for those.  Switch to
388  * Connected state.
389  */
390 static int 
391 netfront_probe(struct xenbus_device *dev, const struct xenbus_device_id *id)
392 {
393         int err;
394         struct ifnet *ifp;
395         struct netfront_info *info;
396
397         printf("netfront_probe() \n");
398         
399         err = create_netdev(dev, &ifp);
400         if (err) {
401                 xenbus_dev_fatal(dev, err, "creating netdev");
402                 return err;
403         }
404
405         info = ifp->if_softc;
406         dev->dev_driver_data = info;
407
408         return 0;
409 }
410
411
412 /**
413  * We are reconnecting to the backend, due to a suspend/resume, or a backend
414  * driver restart.  We tear down our netif structure and recreate it, but
415  * leave the device-layer structures intact so that this is transparent to the
416  * rest of the kernel.
417  */
418 static int 
419 netfront_resume(struct xenbus_device *dev)
420 {
421         struct netfront_info *info = dev->dev_driver_data;
422         
423         DPRINTK("%s\n", dev->nodename);
424         
425         netif_disconnect_backend(info);
426         return (0);
427 }
428
429
430 /* Common code used when first setting up, and when resuming. */
431 static int 
432 talk_to_backend(struct xenbus_device *dev, struct netfront_info *info)
433 {
434         const char *message;
435         struct xenbus_transaction xbt;
436         int err;
437
438         err = xen_net_read_mac(dev, info->mac);
439         if (err) {
440                 xenbus_dev_fatal(dev, err, "parsing %s/mac", dev->nodename);
441                 goto out;
442         }
443
444         /* Create shared ring, alloc event channel. */
445         err = setup_device(dev, info);
446         if (err)
447                 goto out;
448         
449  again:
450         err = xenbus_transaction_start(&xbt);
451         if (err) {
452                 xenbus_dev_fatal(dev, err, "starting transaction");
453                 goto destroy_ring;
454         }
455         err = xenbus_printf(xbt, dev->nodename, "tx-ring-ref","%u",
456                             info->tx_ring_ref);
457         if (err) {
458                 message = "writing tx ring-ref";
459                 goto abort_transaction;
460         }
461         err = xenbus_printf(xbt, dev->nodename, "rx-ring-ref","%u",
462                             info->rx_ring_ref);
463         if (err) {
464                 message = "writing rx ring-ref";
465                 goto abort_transaction;
466         }
467         err = xenbus_printf(xbt, dev->nodename,
468                 "event-channel", "%u", irq_to_evtchn_port(info->irq));
469         if (err) {
470                 message = "writing event-channel";
471                 goto abort_transaction;
472         }
473         err = xenbus_printf(xbt, dev->nodename, "request-rx-copy", "%u",
474                             info->copying_receiver);
475         if (err) {
476                 message = "writing request-rx-copy";
477                 goto abort_transaction;
478         }
479         err = xenbus_printf(xbt, dev->nodename, "feature-rx-notify", "%d", 1);
480         if (err) {
481                 message = "writing feature-rx-notify";
482                 goto abort_transaction;
483         }
484         err = xenbus_printf(xbt, dev->nodename, "feature-no-csum-offload", "%d", 1);
485         if (err) {
486                 message = "writing feature-no-csum-offload";
487                 goto abort_transaction;
488         }
489         err = xenbus_printf(xbt, dev->nodename, "feature-sg", "%d", 1);
490         if (err) {
491                 message = "writing feature-sg";
492                 goto abort_transaction;
493         }
494 #ifdef HAVE_TSO
495         err = xenbus_printf(xbt, dev->nodename, "feature-gso-tcpv4", "%d", 1);
496         if (err) {
497                 message = "writing feature-gso-tcpv4";
498                 goto abort_transaction;
499         }
500 #endif
501
502         err = xenbus_transaction_end(xbt, 0);
503         if (err) {
504                 if (err == EAGAIN)
505                         goto again;
506                 xenbus_dev_fatal(dev, err, "completing transaction");
507                 goto destroy_ring;
508         }
509         
510         return 0;
511         
512  abort_transaction:
513         xenbus_transaction_end(xbt, 1);
514         xenbus_dev_fatal(dev, err, "%s", message);
515  destroy_ring:
516         netif_free(info);
517  out:
518         return err;
519 }
520
521
522 static int 
523 setup_device(struct xenbus_device *dev, struct netfront_info *info)
524 {
525         netif_tx_sring_t *txs;
526         netif_rx_sring_t *rxs;
527         int err;
528         struct ifnet *ifp;
529         
530         ifp = info->xn_ifp;
531
532         info->tx_ring_ref = GRANT_INVALID_REF;
533         info->rx_ring_ref = GRANT_INVALID_REF;
534         info->rx.sring = NULL;
535         info->tx.sring = NULL;
536         info->irq = 0;
537
538         txs = (netif_tx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT|M_ZERO);
539         if (!txs) {
540                 err = ENOMEM;
541                 xenbus_dev_fatal(dev, err, "allocating tx ring page");
542                 goto fail;
543         }
544         SHARED_RING_INIT(txs);
545         FRONT_RING_INIT(&info->tx, txs, PAGE_SIZE);
546         err = xenbus_grant_ring(dev, virt_to_mfn(txs));
547         if (err < 0)
548                 goto fail;
549         info->tx_ring_ref = err;
550
551         rxs = (netif_rx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT|M_ZERO);
552         if (!rxs) {
553                 err = ENOMEM;
554                 xenbus_dev_fatal(dev, err, "allocating rx ring page");
555                 goto fail;
556         }
557         SHARED_RING_INIT(rxs);
558         FRONT_RING_INIT(&info->rx, rxs, PAGE_SIZE);
559
560         err = xenbus_grant_ring(dev, virt_to_mfn(rxs));
561         if (err < 0)
562                 goto fail;
563         info->rx_ring_ref = err;
564
565 #if 0   
566         network_connect(ifp);
567 #endif
568         err = bind_listening_port_to_irqhandler(dev->otherend_id,
569                 "xn", xn_intr, info, INTR_TYPE_NET | INTR_MPSAFE, NULL);
570
571         if (err <= 0) {
572                 xenbus_dev_fatal(dev, err,
573                                  "bind_evtchn_to_irqhandler failed");
574                 goto fail;
575         }
576         info->irq = err;
577         
578         show_device(info);
579         
580         return 0;
581         
582  fail:
583         netif_free(info);
584         return err;
585 }
586
587 /**
588  * Callback received when the backend's state changes.
589  */
590 static void
591 backend_changed(struct xenbus_device *dev,
592                             XenbusState backend_state)
593 {
594                 struct netfront_info *sc = dev->dev_driver_data;
595                 
596         DPRINTK("\n");
597         
598         switch (backend_state) {
599         case XenbusStateInitialising:
600         case XenbusStateInitialised:
601         case XenbusStateConnected:
602         case XenbusStateUnknown:
603         case XenbusStateClosed:
604         case XenbusStateReconfigured:
605         case XenbusStateReconfiguring:
606                         break;
607         case XenbusStateInitWait:
608                 if (dev->state != XenbusStateInitialising)
609                         break;
610                 if (network_connect(sc->xn_ifp) != 0)
611                         break;
612                 xenbus_switch_state(dev, XenbusStateConnected);
613 #ifdef notyet           
614                 (void)send_fake_arp(netdev);
615 #endif          
616                 break;  break;
617         case XenbusStateClosing:
618                         xenbus_frontend_closed(dev);
619                 break;
620         }
621 }
622
623 static void
624 xn_free_rx_ring(struct netfront_info *sc)
625 {
626 #if 0
627         int i;
628         
629         for (i = 0; i < NET_RX_RING_SIZE; i++) {
630                 if (sc->xn_cdata.xn_rx_chain[i] != NULL) {
631                         m_freem(sc->xn_cdata.xn_rx_chain[i]);
632                         sc->xn_cdata.xn_rx_chain[i] = NULL;
633                 }
634         }
635         
636         sc->rx.rsp_cons = 0;
637         sc->xn_rx_if->req_prod = 0;
638         sc->xn_rx_if->event = sc->rx.rsp_cons ;
639 #endif
640 }
641
642 static void
643 xn_free_tx_ring(struct netfront_info *sc)
644 {
645 #if 0
646         int i;
647         
648         for (i = 0; i < NET_TX_RING_SIZE; i++) {
649                 if (sc->xn_cdata.xn_tx_chain[i] != NULL) {
650                         m_freem(sc->xn_cdata.xn_tx_chain[i]);
651                         sc->xn_cdata.xn_tx_chain[i] = NULL;
652                 }
653         }
654         
655         return;
656 #endif
657 }
658
659 static inline int
660 netfront_tx_slot_available(struct netfront_info *np)
661 {
662         return ((np->tx.req_prod_pvt - np->tx.rsp_cons) <
663                 (TX_MAX_TARGET - /* MAX_SKB_FRAGS */ 24 - 2));
664 }
665 static void
666 netif_release_tx_bufs(struct netfront_info *np)
667 {
668         struct mbuf *m;
669         int i;
670
671         for (i = 1; i <= NET_TX_RING_SIZE; i++) {
672                 m = np->xn_cdata.xn_tx_chain[i];
673
674                 if (((u_long)m) < KERNBASE)
675                         continue;
676                 gnttab_grant_foreign_access_ref(np->grant_tx_ref[i],
677                     np->xbdev->otherend_id, virt_to_mfn(mtod(m, vm_offset_t)),
678                     GNTMAP_readonly);
679                 gnttab_release_grant_reference(&np->gref_tx_head,
680                     np->grant_tx_ref[i]);
681                 np->grant_tx_ref[i] = GRANT_INVALID_REF;
682                 add_id_to_freelist(np->tx_mbufs, i);
683                 m_freem(m);
684         }
685 }
686
687 static void
688 network_alloc_rx_buffers(struct netfront_info *sc)
689 {
690         unsigned short id;
691         struct mbuf *m_new;
692         int i, batch_target, notify;
693         RING_IDX req_prod;
694         struct xen_memory_reservation reservation;
695         grant_ref_t ref;
696         int nr_flips;
697         netif_rx_request_t *req;
698         vm_offset_t vaddr;
699         u_long pfn;
700         
701         req_prod = sc->rx.req_prod_pvt;
702
703         if (unlikely(sc->carrier == 0))
704                 return;
705         
706         /*
707          * Allocate skbuffs greedily, even though we batch updates to the
708          * receive ring. This creates a less bursty demand on the memory
709          * allocator, so should reduce the chance of failed allocation
710          * requests both for ourself and for other kernel subsystems.
711          */
712         batch_target = sc->rx_target - (req_prod - sc->rx.rsp_cons);
713         for (i = mbufq_len(&sc->xn_rx_batch); i < batch_target; i++) {
714                 MGETHDR(m_new, M_DONTWAIT, MT_DATA);
715                 if (m_new == NULL) 
716                         goto no_mbuf;
717
718                 m_cljget(m_new, M_DONTWAIT, MJUMPAGESIZE);
719                 if ((m_new->m_flags & M_EXT) == 0) {
720                         m_freem(m_new);
721
722 no_mbuf:
723                         if (i != 0)
724                                 goto refill;
725                         /*
726                          * XXX set timer
727                          */
728                         break;
729                 }
730                 m_new->m_len = m_new->m_pkthdr.len = MJUMPAGESIZE;
731                 
732                 /* queue the mbufs allocated */
733                 mbufq_tail(&sc->xn_rx_batch, m_new);
734         }
735         
736         /* Is the batch large enough to be worthwhile? */
737         if (i < (sc->rx_target/2)) {
738                 if (req_prod >sc->rx.sring->req_prod)
739                         goto push;
740                 return;
741         }
742         /* Adjust floating fill target if we risked running out of buffers. */
743         if ( ((req_prod - sc->rx.sring->rsp_prod) < (sc->rx_target / 4)) &&
744              ((sc->rx_target *= 2) > sc->rx_max_target) )
745                 sc->rx_target = sc->rx_max_target;
746
747 refill:
748         for (nr_flips = i = 0; ; i++) {
749                 if ((m_new = mbufq_dequeue(&sc->xn_rx_batch)) == NULL)
750                         break;
751
752                 m_new->m_ext.ext_arg1 = (vm_paddr_t *)(uintptr_t)(
753                                 vtophys(m_new->m_ext.ext_buf) >> PAGE_SHIFT);
754
755                 id = xennet_rxidx(req_prod + i);
756
757                 KASSERT(sc->xn_cdata.xn_rx_chain[id] == NULL,
758                     ("non-NULL xm_rx_chain"));
759                 sc->xn_cdata.xn_rx_chain[id] = m_new;
760
761                 ref = gnttab_claim_grant_reference(&sc->gref_rx_head);
762                 KASSERT((short)ref >= 0, ("negative ref"));
763                 sc->grant_rx_ref[id] = ref;
764
765                 vaddr = mtod(m_new, vm_offset_t);
766                 pfn = vtophys(vaddr) >> PAGE_SHIFT;
767                 req = RING_GET_REQUEST(&sc->rx, req_prod + i);
768
769                 if (sc->copying_receiver == 0) {
770                         gnttab_grant_foreign_transfer_ref(ref,
771                             sc->xbdev->otherend_id, pfn);
772                         sc->rx_pfn_array[nr_flips] = PFNTOMFN(pfn);
773                         if (!xen_feature(XENFEAT_auto_translated_physmap)) {
774                                 /* Remove this page before passing
775                                  * back to Xen.
776                                  */
777                                 set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
778                                 MULTI_update_va_mapping(&sc->rx_mcl[i],
779                                     vaddr, 0, 0);
780                         }
781                         nr_flips++;
782                 } else {
783                         gnttab_grant_foreign_access_ref(ref,
784                             sc->xbdev->otherend_id,
785                             PFNTOMFN(pfn), 0);
786                 }
787                 req->id = id;
788                 req->gref = ref;
789                 
790                 sc->rx_pfn_array[i] =
791                     vtomach(mtod(m_new,vm_offset_t)) >> PAGE_SHIFT;
792         } 
793         
794         KASSERT(i, ("no mbufs processed")); /* should have returned earlier */
795         KASSERT(mbufq_len(&sc->xn_rx_batch) == 0, ("not all mbufs processed"));
796         /*
797          * We may have allocated buffers which have entries outstanding
798          * in the page * update queue -- make sure we flush those first!
799          */
800         PT_UPDATES_FLUSH();
801         if (nr_flips != 0) {
802 #ifdef notyet
803                 /* Tell the ballon driver what is going on. */
804                 balloon_update_driver_allowance(i);
805 #endif
806                 set_xen_guest_handle(reservation.extent_start, sc->rx_pfn_array);
807                 reservation.nr_extents   = i;
808                 reservation.extent_order = 0;
809                 reservation.address_bits = 0;
810                 reservation.domid        = DOMID_SELF;
811
812                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
813
814                         /* After all PTEs have been zapped, flush the TLB. */
815                         sc->rx_mcl[i-1].args[MULTI_UVMFLAGS_INDEX] =
816                             UVMF_TLB_FLUSH|UVMF_ALL;
817         
818                         /* Give away a batch of pages. */
819                         sc->rx_mcl[i].op = __HYPERVISOR_memory_op;
820                         sc->rx_mcl[i].args[0] = XENMEM_decrease_reservation;
821                         sc->rx_mcl[i].args[1] =  (u_long)&reservation;
822                         /* Zap PTEs and give away pages in one big multicall. */
823                         (void)HYPERVISOR_multicall(sc->rx_mcl, i+1);
824
825                         /* Check return status of HYPERVISOR_dom_mem_op(). */
826                         if (unlikely(sc->rx_mcl[i].result != i))
827                                 panic("Unable to reduce memory reservation\n");
828                         } else {
829                                 if (HYPERVISOR_memory_op(
830                                     XENMEM_decrease_reservation, &reservation)
831                                     != i)
832                                         panic("Unable to reduce memory "
833                                             "reservation\n");
834                 }
835         } else {
836                 wmb();
837         }
838                         
839         /* Above is a suitable barrier to ensure backend will see requests. */
840         sc->rx.req_prod_pvt = req_prod + i;
841 push:
842         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->rx, notify);
843         if (notify)
844                 notify_remote_via_irq(sc->irq);
845 }
846
847 static void
848 xn_rxeof(struct netfront_info *np)
849 {
850         struct ifnet *ifp;
851         struct netfront_rx_info rinfo;
852         struct netif_rx_response *rx = &rinfo.rx;
853         struct netif_extra_info *extras = rinfo.extras;
854         RING_IDX i, rp;
855         multicall_entry_t *mcl;
856         struct mbuf *m;
857         struct mbuf_head rxq, errq;
858         int err, pages_flipped = 0, work_to_do;
859
860         do {
861                 XN_RX_LOCK_ASSERT(np);
862                 if (!netfront_carrier_ok(np))
863                         return;
864
865                 mbufq_init(&errq);
866                 mbufq_init(&rxq);
867
868                 ifp = np->xn_ifp;
869         
870                 rp = np->rx.sring->rsp_prod;
871                 rmb();  /* Ensure we see queued responses up to 'rp'. */
872
873                 i = np->rx.rsp_cons;
874                 while ((i != rp)) {
875                         memcpy(rx, RING_GET_RESPONSE(&np->rx, i), sizeof(*rx));
876                         memset(extras, 0, sizeof(rinfo.extras));
877
878                         m = NULL;
879                         err = xennet_get_responses(np, &rinfo, rp, &m,
880                             &pages_flipped);
881
882                         if (unlikely(err)) {
883                                 if (m)
884                                         mbufq_tail(&errq, m);
885                                 np->stats.rx_errors++;
886                                 i = np->rx.rsp_cons;
887                                 continue;
888                         }
889
890                         m->m_pkthdr.rcvif = ifp;
891                         if ( rx->flags & NETRXF_data_validated ) {
892                                 /* Tell the stack the checksums are okay */
893                                 /*
894                                  * XXX this isn't necessarily the case - need to add
895                                  * check
896                                  */
897                                 
898                                 m->m_pkthdr.csum_flags |=
899                                         (CSUM_IP_CHECKED | CSUM_IP_VALID | CSUM_DATA_VALID
900                                             | CSUM_PSEUDO_HDR);
901                                 m->m_pkthdr.csum_data = 0xffff;
902                         }
903
904                         np->stats.rx_packets++;
905                         np->stats.rx_bytes += m->m_pkthdr.len;
906
907                         mbufq_tail(&rxq, m);
908                         np->rx.rsp_cons = ++i;
909                 }
910
911                 if (pages_flipped) {
912                         /* Some pages are no longer absent... */
913 #ifdef notyet
914                         balloon_update_driver_allowance(-pages_flipped);
915 #endif
916                         /* Do all the remapping work, and M->P updates, in one big
917                          * hypercall.
918                          */
919                         if (!!xen_feature(XENFEAT_auto_translated_physmap)) {
920                                 mcl = np->rx_mcl + pages_flipped;
921                                 mcl->op = __HYPERVISOR_mmu_update;
922                                 mcl->args[0] = (u_long)np->rx_mmu;
923                                 mcl->args[1] = pages_flipped;
924                                 mcl->args[2] = 0;
925                                 mcl->args[3] = DOMID_SELF;
926                                 (void)HYPERVISOR_multicall(np->rx_mcl,
927                                     pages_flipped + 1);
928                         }
929                 }
930         
931                 while ((m = mbufq_dequeue(&errq)))
932                         m_freem(m);
933
934                 /* 
935                  * Process all the mbufs after the remapping is complete.
936                  * Break the mbuf chain first though.
937                  */
938                 while ((m = mbufq_dequeue(&rxq)) != NULL) {
939                         ifp->if_ipackets++;
940                         
941                         /*
942                          * Do we really need to drop the rx lock?
943                          */
944                         XN_RX_UNLOCK(np);
945                         /* Pass it up. */
946                         (*ifp->if_input)(ifp, m);
947                         XN_RX_LOCK(np);
948                 }
949         
950                 np->rx.rsp_cons = i;
951
952 #if 0
953                 /* If we get a callback with very few responses, reduce fill target. */
954                 /* NB. Note exponential increase, linear decrease. */
955                 if (((np->rx.req_prod_pvt - np->rx.sring->rsp_prod) > 
956                         ((3*np->rx_target) / 4)) && (--np->rx_target < np->rx_min_target))
957                         np->rx_target = np->rx_min_target;
958 #endif
959         
960                 network_alloc_rx_buffers(np);
961
962                 RING_FINAL_CHECK_FOR_RESPONSES(&np->rx, work_to_do);
963         } while (work_to_do);
964 }
965
966 static void 
967 xn_txeof(struct netfront_info *np)
968 {
969         RING_IDX i, prod;
970         unsigned short id;
971         struct ifnet *ifp;
972         struct mbuf *m;
973         
974         XN_TX_LOCK_ASSERT(np);
975         
976         if (!netfront_carrier_ok(np))
977                 return;
978         
979         ifp = np->xn_ifp;
980         ifp->if_timer = 0;
981         
982         do {
983                 prod = np->tx.sring->rsp_prod;
984                 rmb(); /* Ensure we see responses up to 'rp'. */
985                 
986                 for (i = np->tx.rsp_cons; i != prod; i++) {
987                         id = RING_GET_RESPONSE(&np->tx, i)->id;
988                         m = np->xn_cdata.xn_tx_chain[id]; 
989                         
990                         ifp->if_opackets++;
991                         KASSERT(m != NULL, ("mbuf not found in xn_tx_chain"));
992                         M_ASSERTVALID(m);
993                         if (unlikely(gnttab_query_foreign_access(
994                             np->grant_tx_ref[id]) != 0)) {
995                                 printf("network_tx_buf_gc: warning "
996                                     "-- grant still in use by backend "
997                                     "domain.\n");
998                                 goto out; 
999                         }
1000                         gnttab_end_foreign_access_ref(
1001                                 np->grant_tx_ref[id]);
1002                         gnttab_release_grant_reference(
1003                                 &np->gref_tx_head, np->grant_tx_ref[id]);
1004                         np->grant_tx_ref[id] = GRANT_INVALID_REF;
1005                         
1006                         np->xn_cdata.xn_tx_chain[id] = NULL;
1007                         add_id_to_freelist(np->xn_cdata.xn_tx_chain, id);
1008                         m_freem(m);
1009                 }
1010                 np->tx.rsp_cons = prod;
1011                 
1012                 /*
1013                  * Set a new event, then check for race with update of
1014                  * tx_cons. Note that it is essential to schedule a
1015                  * callback, no matter how few buffers are pending. Even if
1016                  * there is space in the transmit ring, higher layers may
1017                  * be blocked because too much data is outstanding: in such
1018                  * cases notification from Xen is likely to be the only kick
1019                  * that we'll get.
1020                  */
1021                 np->tx.sring->rsp_event =
1022                     prod + ((np->tx.sring->req_prod - prod) >> 1) + 1;
1023
1024                 mb();
1025                 
1026         } while (prod != np->tx.sring->rsp_prod);
1027         
1028  out: 
1029         if (np->tx_full &&
1030             ((np->tx.sring->req_prod - prod) < NET_TX_RING_SIZE)) {
1031                 np->tx_full = 0;
1032 #if 0
1033                 if (np->user_state == UST_OPEN)
1034                         netif_wake_queue(dev);
1035 #endif
1036         }
1037
1038 }
1039
1040 static void
1041 xn_intr(void *xsc)
1042 {
1043         struct netfront_info *np = xsc;
1044         struct ifnet *ifp = np->xn_ifp;
1045
1046 #if 0
1047         if (!(np->rx.rsp_cons != np->rx.sring->rsp_prod &&
1048             likely(netfront_carrier_ok(np)) &&
1049             ifp->if_drv_flags & IFF_DRV_RUNNING))
1050                 return;
1051 #endif
1052         if (np->tx.rsp_cons != np->tx.sring->rsp_prod) {
1053                 XN_TX_LOCK(np);
1054                 xn_txeof(np);
1055                 XN_TX_UNLOCK(np);                       
1056         }       
1057
1058         XN_RX_LOCK(np);
1059         xn_rxeof(np);
1060         XN_RX_UNLOCK(np);
1061
1062         if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1063             !IFQ_DRV_IS_EMPTY(&ifp->if_snd))
1064                 xn_start(ifp);
1065 }
1066
1067
1068 static void
1069 xennet_move_rx_slot(struct netfront_info *np, struct mbuf *m,
1070         grant_ref_t ref)
1071 {
1072         int new = xennet_rxidx(np->rx.req_prod_pvt);
1073
1074         KASSERT(np->rx_mbufs[new] == NULL, ("rx_mbufs != NULL"));
1075         np->rx_mbufs[new] = m;
1076         np->grant_rx_ref[new] = ref;
1077         RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->id = new;
1078         RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->gref = ref;
1079         np->rx.req_prod_pvt++;
1080 }
1081
1082 static int
1083 xennet_get_extras(struct netfront_info *np,
1084     struct netif_extra_info *extras, RING_IDX rp)
1085 {
1086         struct netif_extra_info *extra;
1087         RING_IDX cons = np->rx.rsp_cons;
1088
1089         int err = 0;
1090
1091         do {
1092                 struct mbuf *m;
1093                 grant_ref_t ref;
1094
1095                 if (unlikely(cons + 1 == rp)) {
1096 #if 0                   
1097                         if (net_ratelimit())
1098                                 WPRINTK("Missing extra info\n");
1099 #endif                  
1100                         err = -EINVAL;
1101                         break;
1102                 }
1103
1104                 extra = (struct netif_extra_info *)
1105                 RING_GET_RESPONSE(&np->rx, ++cons);
1106
1107                 if (unlikely(!extra->type ||
1108                         extra->type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
1109 #if 0                           
1110                         if (net_ratelimit())
1111                                 WPRINTK("Invalid extra type: %d\n",
1112                                         extra->type);
1113 #endif                  
1114                         err = -EINVAL;
1115                 } else {
1116                         memcpy(&extras[extra->type - 1], extra, sizeof(*extra));
1117                 }
1118
1119                 m = xennet_get_rx_mbuf(np, cons);
1120                 ref = xennet_get_rx_ref(np, cons);
1121                 xennet_move_rx_slot(np, m, ref);
1122         } while (extra->flags & XEN_NETIF_EXTRA_FLAG_MORE);
1123
1124         np->rx.rsp_cons = cons;
1125         return err;
1126 }
1127
1128 static int
1129 xennet_get_responses(struct netfront_info *np,
1130         struct netfront_rx_info *rinfo, RING_IDX rp,
1131         struct mbuf  **list,
1132         int *pages_flipped_p)
1133 {
1134         int pages_flipped = *pages_flipped_p;
1135         struct mmu_update *mmu;
1136         struct multicall_entry *mcl;
1137         struct netif_rx_response *rx = &rinfo->rx;
1138         struct netif_extra_info *extras = rinfo->extras;
1139         RING_IDX cons = np->rx.rsp_cons;
1140         struct mbuf *m, *m0, *m_prev;
1141         grant_ref_t ref = xennet_get_rx_ref(np, cons);
1142         int max = 5 /* MAX_SKB_FRAGS + (rx->status <= RX_COPY_THRESHOLD) */;
1143         int frags = 1;
1144         int err = 0;
1145         u_long ret;
1146
1147         m0 = m = m_prev = xennet_get_rx_mbuf(np, cons);
1148
1149         
1150         if (rx->flags & NETRXF_extra_info) {
1151                 err = xennet_get_extras(np, extras, rp);
1152                 cons = np->rx.rsp_cons;
1153         }
1154
1155
1156         if (m0 != NULL) {
1157                         m0->m_pkthdr.len = 0;
1158                         m0->m_next = NULL;
1159         }
1160         
1161         for (;;) {
1162                 u_long mfn;
1163
1164 #if 0           
1165                 printf("rx->status=%hd rx->offset=%hu frags=%u\n",
1166                         rx->status, rx->offset, frags);
1167 #endif
1168                 if (unlikely(rx->status < 0 ||
1169                         rx->offset + rx->status > PAGE_SIZE)) {
1170 #if 0                                           
1171                         if (net_ratelimit())
1172                                 WPRINTK("rx->offset: %x, size: %u\n",
1173                                         rx->offset, rx->status);
1174 #endif                                          
1175                         xennet_move_rx_slot(np, m, ref);
1176                         err = -EINVAL;
1177                         goto next;
1178                 }
1179                 
1180                 /*
1181                  * This definitely indicates a bug, either in this driver or in
1182                  * the backend driver. In future this should flag the bad
1183                  * situation to the system controller to reboot the backed.
1184                  */
1185                 if (ref == GRANT_INVALID_REF) {
1186 #if 0                           
1187                         if (net_ratelimit())
1188                                 WPRINTK("Bad rx response id %d.\n", rx->id);
1189 #endif                  
1190                         err = -EINVAL;
1191                         goto next;
1192                 }
1193
1194                 if (!np->copying_receiver) {
1195                         /* Memory pressure, insufficient buffer
1196                          * headroom, ...
1197                          */
1198                         if (!(mfn = gnttab_end_foreign_transfer_ref(ref))) {
1199                                 if (net_ratelimit())
1200                                         WPRINTK("Unfulfilled rx req "
1201                                                 "(id=%d, st=%d).\n",
1202                                                 rx->id, rx->status);
1203                                 xennet_move_rx_slot(np, m, ref);
1204                                 err = -ENOMEM;
1205                                 goto next;
1206                         }
1207
1208                         if (!xen_feature( XENFEAT_auto_translated_physmap)) {
1209                                 /* Remap the page. */
1210                                 void *vaddr = mtod(m, void *);
1211                                 uint32_t pfn;
1212
1213                                 mcl = np->rx_mcl + pages_flipped;
1214                                 mmu = np->rx_mmu + pages_flipped;
1215
1216                                 MULTI_update_va_mapping(mcl, (u_long)vaddr,
1217                                     (((vm_paddr_t)mfn) << PAGE_SHIFT) | PG_RW |
1218                                     PG_V | PG_M | PG_A, 0);
1219                                 pfn = (uint32_t)m->m_ext.ext_arg1;
1220                                 mmu->ptr = ((vm_paddr_t)mfn << PAGE_SHIFT) |
1221                                     MMU_MACHPHYS_UPDATE;
1222                                 mmu->val = pfn;
1223
1224                                 set_phys_to_machine(pfn, mfn);
1225                         }
1226                         pages_flipped++;
1227                 } else {
1228                         ret = gnttab_end_foreign_access_ref(ref);
1229                         KASSERT(ret, ("ret != 0"));
1230                 }
1231
1232                 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1233
1234 next:
1235                 if (m != NULL) {
1236                                 m->m_len = rx->status;
1237                                 m->m_data += rx->offset;
1238                                 m0->m_pkthdr.len += rx->status;
1239                 }
1240                 
1241                 if (!(rx->flags & NETRXF_more_data))
1242                         break;
1243
1244                 if (cons + frags == rp) {
1245                         if (net_ratelimit())
1246                                 WPRINTK("Need more frags\n");
1247                         err = -ENOENT;
1248                                 break;
1249                 }
1250                 m_prev = m;
1251                 
1252                 rx = RING_GET_RESPONSE(&np->rx, cons + frags);
1253                 m = xennet_get_rx_mbuf(np, cons + frags);
1254
1255                 m_prev->m_next = m;
1256                 m->m_next = NULL;
1257                 ref = xennet_get_rx_ref(np, cons + frags);
1258                 frags++;
1259         }
1260         *list = m0;
1261
1262         if (unlikely(frags > max)) {
1263                 if (net_ratelimit())
1264                         WPRINTK("Too many frags\n");
1265                 err = -E2BIG;
1266         }
1267
1268         if (unlikely(err))
1269                 np->rx.rsp_cons = cons + frags;
1270
1271         *pages_flipped_p = pages_flipped;
1272
1273         return err;
1274 }
1275
1276 static void
1277 xn_tick_locked(struct netfront_info *sc) 
1278 {
1279         XN_RX_LOCK_ASSERT(sc);
1280         callout_reset(&sc->xn_stat_ch, hz, xn_tick, sc);
1281
1282         /* XXX placeholder for printing debug information */
1283      
1284 }
1285
1286
1287 static void
1288 xn_tick(void *xsc) 
1289 {
1290         struct netfront_info *sc;
1291     
1292         sc = xsc;
1293         XN_RX_LOCK(sc);
1294         xn_tick_locked(sc);
1295         XN_RX_UNLOCK(sc);
1296      
1297 }
1298 static void
1299 xn_start_locked(struct ifnet *ifp) 
1300 {
1301         unsigned short id;
1302         struct mbuf *m_head, *new_m;
1303         struct netfront_info *sc;
1304         netif_tx_request_t *tx;
1305         RING_IDX i;
1306         grant_ref_t ref;
1307         u_long mfn, tx_bytes;
1308         int notify;
1309
1310         sc = ifp->if_softc;
1311         tx_bytes = 0;
1312
1313         if (!netfront_carrier_ok(sc))
1314                 return;
1315         
1316         for (i = sc->tx.req_prod_pvt; TRUE; i++) {
1317                 IF_DEQUEUE(&ifp->if_snd, m_head);
1318                 if (m_head == NULL) 
1319                         break;
1320                 
1321                 if (!netfront_tx_slot_available(sc)) {
1322                         IF_PREPEND(&ifp->if_snd, m_head);
1323                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1324                         break;
1325                 }
1326                 
1327                 id = get_id_from_freelist(sc->xn_cdata.xn_tx_chain);
1328
1329                 /*
1330                  * Start packing the mbufs in this chain into
1331                  * the fragment pointers. Stop when we run out
1332                  * of fragments or hit the end of the mbuf chain.
1333                  */
1334                 new_m = makembuf(m_head);
1335                 tx = RING_GET_REQUEST(&sc->tx, i);
1336                 tx->id = id;
1337                 ref = gnttab_claim_grant_reference(&sc->gref_tx_head);
1338                 KASSERT((short)ref >= 0, ("Negative ref"));
1339                 mfn = virt_to_mfn(mtod(new_m, vm_offset_t));
1340                 gnttab_grant_foreign_access_ref(ref, sc->xbdev->otherend_id,
1341                     mfn, GNTMAP_readonly);
1342                 tx->gref = sc->grant_tx_ref[id] = ref;
1343                 tx->size = new_m->m_pkthdr.len;
1344 #if 0
1345                 tx->flags = (skb->ip_summed == CHECKSUM_HW) ? NETTXF_csum_blank : 0;
1346 #endif
1347                 tx->flags = 0;
1348                 new_m->m_next = NULL;
1349                 new_m->m_nextpkt = NULL;
1350
1351                 m_freem(m_head);
1352
1353                 sc->xn_cdata.xn_tx_chain[id] = new_m;
1354                 BPF_MTAP(ifp, new_m);
1355
1356                 sc->stats.tx_bytes += new_m->m_pkthdr.len;
1357                 sc->stats.tx_packets++;
1358         }
1359
1360         sc->tx.req_prod_pvt = i;
1361         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->tx, notify);
1362         if (notify)
1363                 notify_remote_via_irq(sc->irq);
1364
1365         xn_txeof(sc);
1366
1367         if (RING_FULL(&sc->tx)) {
1368                 sc->tx_full = 1;
1369 #if 0
1370                 netif_stop_queue(dev);
1371 #endif
1372         }
1373
1374         return;
1375 }    
1376
1377 static void
1378 xn_start(struct ifnet *ifp)
1379 {
1380         struct netfront_info *sc;
1381         sc = ifp->if_softc;
1382         XN_TX_LOCK(sc);
1383         xn_start_locked(ifp);
1384         XN_TX_UNLOCK(sc);
1385 }
1386
1387 /* equivalent of network_open() in Linux */
1388 static void 
1389 xn_ifinit_locked(struct netfront_info *sc) 
1390 {
1391         struct ifnet *ifp;
1392         
1393         XN_LOCK_ASSERT(sc);
1394         
1395         ifp = sc->xn_ifp;
1396         
1397         if (ifp->if_drv_flags & IFF_DRV_RUNNING) 
1398                 return;
1399         
1400         xn_stop(sc);
1401         
1402         network_alloc_rx_buffers(sc);
1403         sc->rx.sring->rsp_event = sc->rx.rsp_cons + 1;
1404         
1405         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1406         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1407         
1408         callout_reset(&sc->xn_stat_ch, hz, xn_tick, sc);
1409
1410 }
1411
1412
1413 static void 
1414 xn_ifinit(void *xsc)
1415 {
1416         struct netfront_info *sc = xsc;
1417     
1418         XN_LOCK(sc);
1419         xn_ifinit_locked(sc);
1420         XN_UNLOCK(sc);
1421
1422 }
1423
1424
1425 static int
1426 xn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1427 {
1428         struct netfront_info *sc = ifp->if_softc;
1429         struct ifreq *ifr = (struct ifreq *) data;
1430         struct ifaddr *ifa = (struct ifaddr *)data;
1431
1432         int mask, error = 0;
1433         switch(cmd) {
1434         case SIOCSIFADDR:
1435         case SIOCGIFADDR:
1436                 XN_LOCK(sc);
1437                 if (ifa->ifa_addr->sa_family == AF_INET) {
1438                         ifp->if_flags |= IFF_UP;
1439                         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) 
1440                                 xn_ifinit_locked(sc);
1441                         arp_ifinit(ifp, ifa);
1442                         XN_UNLOCK(sc);
1443                 } else {
1444                         XN_UNLOCK(sc);
1445                         error = ether_ioctl(ifp, cmd, data);
1446                 }
1447                 break;
1448         case SIOCSIFMTU:
1449                 /* XXX can we alter the MTU on a VN ?*/
1450 #ifdef notyet
1451                 if (ifr->ifr_mtu > XN_JUMBO_MTU)
1452                         error = EINVAL;
1453                 else 
1454 #endif
1455                 {
1456                         ifp->if_mtu = ifr->ifr_mtu;
1457                         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1458                         xn_ifinit(sc);
1459                 }
1460                 break;
1461         case SIOCSIFFLAGS:
1462                 XN_LOCK(sc);
1463                 if (ifp->if_flags & IFF_UP) {
1464                         /*
1465                          * If only the state of the PROMISC flag changed,
1466                          * then just use the 'set promisc mode' command
1467                          * instead of reinitializing the entire NIC. Doing
1468                          * a full re-init means reloading the firmware and
1469                          * waiting for it to start up, which may take a
1470                          * second or two.
1471                          */
1472 #ifdef notyet
1473                         /* No promiscuous mode with Xen */
1474                         if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1475                             ifp->if_flags & IFF_PROMISC &&
1476                             !(sc->xn_if_flags & IFF_PROMISC)) {
1477                                 XN_SETBIT(sc, XN_RX_MODE,
1478                                           XN_RXMODE_RX_PROMISC);
1479                         } else if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1480                                    !(ifp->if_flags & IFF_PROMISC) &&
1481                                    sc->xn_if_flags & IFF_PROMISC) {
1482                                 XN_CLRBIT(sc, XN_RX_MODE,
1483                                           XN_RXMODE_RX_PROMISC);
1484                         } else
1485 #endif
1486                                 xn_ifinit_locked(sc);
1487                 } else {
1488                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1489                                 xn_stop(sc);
1490                         }
1491                 }
1492                 sc->xn_if_flags = ifp->if_flags;
1493                 XN_UNLOCK(sc);
1494                 error = 0;
1495                 break;
1496         case SIOCSIFCAP:
1497                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1498                 if (mask & IFCAP_HWCSUM) {
1499                         if (IFCAP_HWCSUM & ifp->if_capenable)
1500                                 ifp->if_capenable &= ~IFCAP_HWCSUM;
1501                         else
1502                                 ifp->if_capenable |= IFCAP_HWCSUM;
1503                 }
1504                 error = 0;
1505                 break;
1506         case SIOCADDMULTI:
1507         case SIOCDELMULTI:
1508 #ifdef notyet
1509                 if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1510                         XN_LOCK(sc);
1511                         xn_setmulti(sc);
1512                         XN_UNLOCK(sc);
1513                         error = 0;
1514                 }
1515 #endif
1516                 /* FALLTHROUGH */
1517         case SIOCSIFMEDIA:
1518         case SIOCGIFMEDIA:
1519                 error = EINVAL;
1520                 break;
1521         default:
1522                 error = ether_ioctl(ifp, cmd, data);
1523         }
1524     
1525         return (error);
1526 }
1527
1528 static void
1529 xn_stop(struct netfront_info *sc)
1530 {       
1531         struct ifnet *ifp;
1532
1533         XN_LOCK_ASSERT(sc);
1534     
1535         ifp = sc->xn_ifp;
1536
1537         callout_stop(&sc->xn_stat_ch);
1538
1539         xn_free_rx_ring(sc);
1540         xn_free_tx_ring(sc);
1541     
1542         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1543 }
1544
1545 /* START of Xenolinux helper functions adapted to FreeBSD */
1546 static int
1547 network_connect(struct ifnet *ifp)
1548 {
1549         struct netfront_info *np;
1550         int i, requeue_idx, err;
1551         grant_ref_t ref;
1552         netif_rx_request_t *req;
1553         u_int feature_rx_copy, feature_rx_flip;
1554
1555         printf("network_connect\n");
1556         
1557         np = ifp->if_softc;
1558         err = xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1559                            "feature-rx-copy", "%u", &feature_rx_copy);
1560         if (err != 1)
1561                 feature_rx_copy = 0;
1562         err = xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1563                            "feature-rx-flip", "%u", &feature_rx_flip);
1564         if (err != 1)
1565                 feature_rx_flip = 1;
1566
1567         /*
1568          * Copy packets on receive path if:
1569          *  (a) This was requested by user, and the backend supports it; or
1570          *  (b) Flipping was requested, but this is unsupported by the backend.
1571          */
1572         np->copying_receiver = ((MODPARM_rx_copy && feature_rx_copy) ||
1573                                 (MODPARM_rx_flip && !feature_rx_flip));
1574
1575         XN_LOCK(np);
1576         /* Recovery procedure: */
1577         err = talk_to_backend(np->xbdev, np);
1578         if (err) 
1579                         return (err);
1580         
1581         /* Step 1: Reinitialise variables. */
1582         netif_release_tx_bufs(np);
1583
1584         /* Step 2: Rebuild the RX buffer freelist and the RX ring itself. */
1585         for (requeue_idx = 0, i = 0; i < NET_RX_RING_SIZE; i++) {
1586                 struct mbuf *m;
1587
1588                 if (np->rx_mbufs[i] == NULL)
1589                         continue;
1590
1591                 m = np->rx_mbufs[requeue_idx] = xennet_get_rx_mbuf(np, i);
1592                 ref = np->grant_rx_ref[requeue_idx] = xennet_get_rx_ref(np, i);
1593                 req = RING_GET_REQUEST(&np->rx, requeue_idx);
1594
1595                 if (!np->copying_receiver) {
1596                         gnttab_grant_foreign_transfer_ref(ref,
1597                             np->xbdev->otherend_id,
1598                             vtophys(mtod(m, vm_offset_t)));
1599                 } else {
1600                         gnttab_grant_foreign_access_ref(ref,
1601                             np->xbdev->otherend_id,
1602                             vtophys(mtod(m, vm_offset_t)), 0);
1603                 }
1604                 req->gref = ref;
1605                 req->id   = requeue_idx;
1606
1607                 requeue_idx++;
1608         }
1609
1610         np->rx.req_prod_pvt = requeue_idx;
1611         
1612         /* Step 3: All public and private state should now be sane.  Get
1613          * ready to start sending and receiving packets and give the driver
1614          * domain a kick because we've probably just requeued some
1615          * packets.
1616          */
1617         netfront_carrier_on(np);
1618         notify_remote_via_irq(np->irq);
1619         XN_TX_LOCK(np);
1620         xn_txeof(np);
1621         XN_TX_UNLOCK(np);
1622         network_alloc_rx_buffers(np);
1623         XN_UNLOCK(np);
1624
1625         return (0);
1626 }
1627
1628
1629 static void 
1630 show_device(struct netfront_info *sc)
1631 {
1632 #ifdef DEBUG
1633         if (sc) {
1634                 IPRINTK("<vif handle=%u %s(%s) evtchn=%u irq=%u tx=%p rx=%p>\n",
1635                         sc->xn_ifno,
1636                         be_state_name[sc->xn_backend_state],
1637                         sc->xn_user_state ? "open" : "closed",
1638                         sc->xn_evtchn,
1639                         sc->xn_irq,
1640                         sc->xn_tx_if,
1641                         sc->xn_rx_if);
1642         } else {
1643                 IPRINTK("<vif NULL>\n");
1644         }
1645 #endif
1646 }
1647
1648 static int ifno = 0;
1649
1650 /** Create a network device.
1651  * @param handle device handle
1652  */
1653 static int 
1654 create_netdev(struct xenbus_device *dev, struct ifnet **ifpp)
1655 {
1656         int i;
1657         struct netfront_info *np;
1658         int err;
1659         struct ifnet *ifp;
1660
1661         np = (struct netfront_info *)malloc(sizeof(struct netfront_info),
1662             M_DEVBUF, M_NOWAIT);
1663         if (np == NULL)
1664                         return (ENOMEM);
1665         
1666         memset(np, 0, sizeof(struct netfront_info));
1667         
1668         np->xbdev         = dev;
1669     
1670         XN_LOCK_INIT(np, xennetif);
1671         np->rx_target     = RX_MIN_TARGET;
1672         np->rx_min_target = RX_MIN_TARGET;
1673         np->rx_max_target = RX_MAX_TARGET;
1674         
1675         /* Initialise {tx,rx}_skbs to be a free chain containing every entry. */
1676         for (i = 0; i <= NET_TX_RING_SIZE; i++) {
1677                 np->tx_mbufs[i] = (void *) ((u_long) i+1);
1678                 np->grant_tx_ref[i] = GRANT_INVALID_REF;        
1679         }
1680         for (i = 0; i <= NET_RX_RING_SIZE; i++) {
1681                 np->rx_mbufs[i] = NULL;
1682                 np->grant_rx_ref[i] = GRANT_INVALID_REF;
1683         }
1684         /* A grant for every tx ring slot */
1685         if (gnttab_alloc_grant_references(TX_MAX_TARGET,
1686                                           &np->gref_tx_head) < 0) {
1687                 printf("#### netfront can't alloc tx grant refs\n");
1688                 err = ENOMEM;
1689                 goto exit;
1690         }
1691         /* A grant for every rx ring slot */
1692         if (gnttab_alloc_grant_references(RX_MAX_TARGET,
1693                                           &np->gref_rx_head) < 0) {
1694                 printf("#### netfront can't alloc rx grant refs\n");
1695                 gnttab_free_grant_references(np->gref_tx_head);
1696                 err = ENOMEM;
1697                 goto exit;
1698         }
1699         
1700         err = xen_net_read_mac(dev, np->mac);
1701         if (err) {
1702                 xenbus_dev_fatal(dev, err, "parsing %s/mac", dev->nodename);
1703                 goto out;
1704         }
1705         
1706         /* Set up ifnet structure */
1707         *ifpp = ifp = np->xn_ifp = if_alloc(IFT_ETHER);
1708         ifp->if_softc = np;
1709         if_initname(ifp, "xn",  ifno++/* ifno */);
1710         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX;
1711         ifp->if_ioctl = xn_ioctl;
1712         ifp->if_output = ether_output;
1713         ifp->if_start = xn_start;
1714 #ifdef notyet
1715         ifp->if_watchdog = xn_watchdog;
1716 #endif
1717         ifp->if_init = xn_ifinit;
1718         ifp->if_mtu = ETHERMTU;
1719         ifp->if_snd.ifq_maxlen = NET_TX_RING_SIZE - 1;
1720         
1721 #ifdef notyet
1722         ifp->if_hwassist = XN_CSUM_FEATURES;
1723         ifp->if_capabilities = IFCAP_HWCSUM;
1724         ifp->if_capenable = ifp->if_capabilities;
1725 #endif    
1726         
1727         ether_ifattach(ifp, np->mac);
1728         callout_init(&np->xn_stat_ch, CALLOUT_MPSAFE);
1729         netfront_carrier_off(np);
1730
1731         return (0);
1732
1733 exit:
1734         gnttab_free_grant_references(np->gref_tx_head);
1735 out:
1736         panic("do something smart");
1737
1738 }
1739
1740 /**
1741  * Handle the change of state of the backend to Closing.  We must delete our
1742  * device-layer structures now, to ensure that writes are flushed through to
1743  * the backend.  Once is this done, we can switch to Closed in
1744  * acknowledgement.
1745  */
1746 #if 0
1747 static void netfront_closing(struct xenbus_device *dev)
1748 {
1749 #if 0
1750         struct netfront_info *info = dev->dev_driver_data;
1751
1752         DPRINTK("netfront_closing: %s removed\n", dev->nodename);
1753
1754         close_netdev(info);
1755 #endif
1756         xenbus_switch_state(dev, XenbusStateClosed);
1757 }
1758 #endif
1759
1760 static int netfront_remove(struct xenbus_device *dev)
1761 {
1762         struct netfront_info *info = dev->dev_driver_data;
1763
1764         DPRINTK("%s\n", dev->nodename);
1765
1766         netif_free(info);
1767         free(info, M_DEVBUF);
1768
1769         return 0;
1770 }
1771
1772
1773 static void netif_free(struct netfront_info *info)
1774 {
1775         netif_disconnect_backend(info);
1776 #if 0
1777         close_netdev(info);
1778 #endif
1779 }
1780
1781
1782
1783 static void netif_disconnect_backend(struct netfront_info *info)
1784 {
1785         xn_stop(info);
1786         end_access(info->tx_ring_ref, info->tx.sring);
1787         end_access(info->rx_ring_ref, info->rx.sring);
1788         info->tx_ring_ref = GRANT_INVALID_REF;
1789         info->rx_ring_ref = GRANT_INVALID_REF;
1790         info->tx.sring = NULL;
1791         info->rx.sring = NULL;
1792
1793 #if 0
1794         if (info->irq)
1795                 unbind_from_irqhandler(info->irq, info->netdev);
1796 #else 
1797         panic("FIX ME");
1798 #endif
1799         info->irq = 0;
1800 }
1801
1802
1803 static void end_access(int ref, void *page)
1804 {
1805         if (ref != GRANT_INVALID_REF)
1806                 gnttab_end_foreign_access(ref, page);
1807 }
1808
1809
1810 /* ** Driver registration ** */
1811
1812
1813 static struct xenbus_device_id netfront_ids[] = {
1814         { "vif" },
1815         { "" }
1816 };
1817
1818
1819 static struct xenbus_driver netfront = {
1820         .name = "vif",
1821         .ids = netfront_ids,
1822         .probe = netfront_probe,
1823         .remove = netfront_remove,
1824         .resume = netfront_resume,
1825         .otherend_changed = backend_changed,
1826 };
1827
1828 static void
1829 netif_init(void *unused)
1830 {
1831         if (!is_running_on_xen())
1832                 return;
1833
1834         if (is_initial_xendomain())
1835                 return;
1836
1837         IPRINTK("Initialising virtual ethernet driver.\n");
1838
1839         xenbus_register_frontend(&netfront);
1840 }
1841
1842 SYSINIT(xennetif, SI_SUB_PSEUDO, SI_ORDER_SECOND, netif_init, NULL);
1843
1844
1845 /*
1846  * Local variables:
1847  * mode: C
1848  * c-set-style: "BSD"
1849  * c-basic-offset: 8
1850  * tab-width: 4
1851  * indent-tabs-mode: t
1852  * End:
1853  */