Merge branch 'master' of git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6
[linux-2.6] / drivers / net / iseries_veth.c
1 /* File veth.c created by Kyle A. Lucke on Mon Aug  7 2000. */
2 /*
3  * IBM eServer iSeries Virtual Ethernet Device Driver
4  * Copyright (C) 2001 Kyle A. Lucke (klucke@us.ibm.com), IBM Corp.
5  * Substantially cleaned up by:
6  * Copyright (C) 2003 David Gibson <dwg@au1.ibm.com>, IBM Corporation.
7  * Copyright (C) 2004-2005 Michael Ellerman, IBM Corporation.
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License as
11  * published by the Free Software Foundation; either version 2 of the
12  * License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22  * USA
23  *
24  *
25  * This module implements the virtual ethernet device for iSeries LPAR
26  * Linux.  It uses hypervisor message passing to implement an
27  * ethernet-like network device communicating between partitions on
28  * the iSeries.
29  *
30  * The iSeries LPAR hypervisor currently allows for up to 16 different
31  * virtual ethernets.  These are all dynamically configurable on
32  * OS/400 partitions, but dynamic configuration is not supported under
33  * Linux yet.  An ethXX network device will be created for each
34  * virtual ethernet this partition is connected to.
35  *
36  * - This driver is responsible for routing packets to and from other
37  *   partitions.  The MAC addresses used by the virtual ethernets
38  *   contains meaning and must not be modified.
39  *
40  * - Having 2 virtual ethernets to the same remote partition DOES NOT
41  *   double the available bandwidth.  The 2 devices will share the
42  *   available hypervisor bandwidth.
43  *
44  * - If you send a packet to your own mac address, it will just be
45  *   dropped, you won't get it on the receive side.
46  *
47  * - Multicast is implemented by sending the frame frame to every
48  *   other partition.  It is the responsibility of the receiving
49  *   partition to filter the addresses desired.
50  *
51  * Tunable parameters:
52  *
53  * VETH_NUMBUFFERS: This compile time option defaults to 120.  It
54  * controls how much memory Linux will allocate per remote partition
55  * it is communicating with.  It can be thought of as the maximum
56  * number of packets outstanding to a remote partition at a time.
57  */
58
59 #include <linux/module.h>
60 #include <linux/types.h>
61 #include <linux/errno.h>
62 #include <linux/ioport.h>
63 #include <linux/kernel.h>
64 #include <linux/netdevice.h>
65 #include <linux/etherdevice.h>
66 #include <linux/skbuff.h>
67 #include <linux/init.h>
68 #include <linux/delay.h>
69 #include <linux/mm.h>
70 #include <linux/ethtool.h>
71 #include <linux/if_ether.h>
72
73 #include <asm/abs_addr.h>
74 #include <asm/iseries/mf.h>
75 #include <asm/uaccess.h>
76
77 #include <asm/iseries/hv_lp_config.h>
78 #include <asm/iseries/hv_types.h>
79 #include <asm/iseries/hv_lp_event.h>
80 #include <asm/iommu.h>
81 #include <asm/vio.h>
82
83 #undef DEBUG
84
85 MODULE_AUTHOR("Kyle Lucke <klucke@us.ibm.com>");
86 MODULE_DESCRIPTION("iSeries Virtual ethernet driver");
87 MODULE_LICENSE("GPL");
88
89 #define VETH_EVENT_CAP  (0)
90 #define VETH_EVENT_FRAMES       (1)
91 #define VETH_EVENT_MONITOR      (2)
92 #define VETH_EVENT_FRAMES_ACK   (3)
93
94 #define VETH_MAX_ACKS_PER_MSG   (20)
95 #define VETH_MAX_FRAMES_PER_MSG (6)
96
97 struct veth_frames_data {
98         u32 addr[VETH_MAX_FRAMES_PER_MSG];
99         u16 len[VETH_MAX_FRAMES_PER_MSG];
100         u32 eofmask;
101 };
102 #define VETH_EOF_SHIFT          (32-VETH_MAX_FRAMES_PER_MSG)
103
104 struct veth_frames_ack_data {
105         u16 token[VETH_MAX_ACKS_PER_MSG];
106 };
107
108 struct veth_cap_data {
109         u8 caps_version;
110         u8 rsvd1;
111         u16 num_buffers;
112         u16 ack_threshold;
113         u16 rsvd2;
114         u32 ack_timeout;
115         u32 rsvd3;
116         u64 rsvd4[3];
117 };
118
119 struct veth_lpevent {
120         struct HvLpEvent base_event;
121         union {
122                 struct veth_cap_data caps_data;
123                 struct veth_frames_data frames_data;
124                 struct veth_frames_ack_data frames_ack_data;
125         } u;
126
127 };
128
129 #define DRV_NAME        "iseries_veth"
130 #define DRV_VERSION     "2.0"
131
132 #define VETH_NUMBUFFERS         (120)
133 #define VETH_ACKTIMEOUT         (1000000) /* microseconds */
134 #define VETH_MAX_MCAST          (12)
135
136 #define VETH_MAX_MTU            (9000)
137
138 #if VETH_NUMBUFFERS < 10
139 #define ACK_THRESHOLD           (1)
140 #elif VETH_NUMBUFFERS < 20
141 #define ACK_THRESHOLD           (4)
142 #elif VETH_NUMBUFFERS < 40
143 #define ACK_THRESHOLD           (10)
144 #else
145 #define ACK_THRESHOLD           (20)
146 #endif
147
148 #define VETH_STATE_SHUTDOWN     (0x0001)
149 #define VETH_STATE_OPEN         (0x0002)
150 #define VETH_STATE_RESET        (0x0004)
151 #define VETH_STATE_SENTMON      (0x0008)
152 #define VETH_STATE_SENTCAPS     (0x0010)
153 #define VETH_STATE_GOTCAPACK    (0x0020)
154 #define VETH_STATE_GOTCAPS      (0x0040)
155 #define VETH_STATE_SENTCAPACK   (0x0080)
156 #define VETH_STATE_READY        (0x0100)
157
158 struct veth_msg {
159         struct veth_msg *next;
160         struct veth_frames_data data;
161         int token;
162         int in_use;
163         struct sk_buff *skb;
164         struct device *dev;
165 };
166
167 struct veth_lpar_connection {
168         HvLpIndex remote_lp;
169         struct delayed_work statemachine_wq;
170         struct veth_msg *msgs;
171         int num_events;
172         struct veth_cap_data local_caps;
173
174         struct kobject kobject;
175         struct timer_list ack_timer;
176
177         struct timer_list reset_timer;
178         unsigned int reset_timeout;
179         unsigned long last_contact;
180         int outstanding_tx;
181
182         spinlock_t lock;
183         unsigned long state;
184         HvLpInstanceId src_inst;
185         HvLpInstanceId dst_inst;
186         struct veth_lpevent cap_event, cap_ack_event;
187         u16 pending_acks[VETH_MAX_ACKS_PER_MSG];
188         u32 num_pending_acks;
189
190         int num_ack_events;
191         struct veth_cap_data remote_caps;
192         u32 ack_timeout;
193
194         struct veth_msg *msg_stack_head;
195 };
196
197 struct veth_port {
198         struct device *dev;
199         struct net_device_stats stats;
200         u64 mac_addr;
201         HvLpIndexMap lpar_map;
202
203         /* queue_lock protects the stopped_map and dev's queue. */
204         spinlock_t queue_lock;
205         HvLpIndexMap stopped_map;
206
207         /* mcast_gate protects promiscuous, num_mcast & mcast_addr. */
208         rwlock_t mcast_gate;
209         int promiscuous;
210         int num_mcast;
211         u64 mcast_addr[VETH_MAX_MCAST];
212
213         struct kobject kobject;
214 };
215
216 static HvLpIndex this_lp;
217 static struct veth_lpar_connection *veth_cnx[HVMAXARCHITECTEDLPS]; /* = 0 */
218 static struct net_device *veth_dev[HVMAXARCHITECTEDVIRTUALLANS]; /* = 0 */
219
220 static int veth_start_xmit(struct sk_buff *skb, struct net_device *dev);
221 static void veth_recycle_msg(struct veth_lpar_connection *, struct veth_msg *);
222 static void veth_wake_queues(struct veth_lpar_connection *cnx);
223 static void veth_stop_queues(struct veth_lpar_connection *cnx);
224 static void veth_receive(struct veth_lpar_connection *, struct veth_lpevent *);
225 static void veth_release_connection(struct kobject *kobject);
226 static void veth_timed_ack(unsigned long ptr);
227 static void veth_timed_reset(unsigned long ptr);
228
229 /*
230  * Utility functions
231  */
232
233 #define veth_info(fmt, args...) \
234         printk(KERN_INFO DRV_NAME ": " fmt, ## args)
235
236 #define veth_error(fmt, args...) \
237         printk(KERN_ERR DRV_NAME ": Error: " fmt, ## args)
238
239 #ifdef DEBUG
240 #define veth_debug(fmt, args...) \
241         printk(KERN_DEBUG DRV_NAME ": " fmt, ## args)
242 #else
243 #define veth_debug(fmt, args...) do {} while (0)
244 #endif
245
246 /* You must hold the connection's lock when you call this function. */
247 static inline void veth_stack_push(struct veth_lpar_connection *cnx,
248                                    struct veth_msg *msg)
249 {
250         msg->next = cnx->msg_stack_head;
251         cnx->msg_stack_head = msg;
252 }
253
254 /* You must hold the connection's lock when you call this function. */
255 static inline struct veth_msg *veth_stack_pop(struct veth_lpar_connection *cnx)
256 {
257         struct veth_msg *msg;
258
259         msg = cnx->msg_stack_head;
260         if (msg)
261                 cnx->msg_stack_head = cnx->msg_stack_head->next;
262
263         return msg;
264 }
265
266 /* You must hold the connection's lock when you call this function. */
267 static inline int veth_stack_is_empty(struct veth_lpar_connection *cnx)
268 {
269         return cnx->msg_stack_head == NULL;
270 }
271
272 static inline HvLpEvent_Rc
273 veth_signalevent(struct veth_lpar_connection *cnx, u16 subtype,
274                  HvLpEvent_AckInd ackind, HvLpEvent_AckType acktype,
275                  u64 token,
276                  u64 data1, u64 data2, u64 data3, u64 data4, u64 data5)
277 {
278         return HvCallEvent_signalLpEventFast(cnx->remote_lp,
279                                              HvLpEvent_Type_VirtualLan,
280                                              subtype, ackind, acktype,
281                                              cnx->src_inst,
282                                              cnx->dst_inst,
283                                              token, data1, data2, data3,
284                                              data4, data5);
285 }
286
287 static inline HvLpEvent_Rc veth_signaldata(struct veth_lpar_connection *cnx,
288                                            u16 subtype, u64 token, void *data)
289 {
290         u64 *p = (u64 *) data;
291
292         return veth_signalevent(cnx, subtype, HvLpEvent_AckInd_NoAck,
293                                 HvLpEvent_AckType_ImmediateAck,
294                                 token, p[0], p[1], p[2], p[3], p[4]);
295 }
296
297 struct veth_allocation {
298         struct completion c;
299         int num;
300 };
301
302 static void veth_complete_allocation(void *parm, int number)
303 {
304         struct veth_allocation *vc = (struct veth_allocation *)parm;
305
306         vc->num = number;
307         complete(&vc->c);
308 }
309
310 static int veth_allocate_events(HvLpIndex rlp, int number)
311 {
312         struct veth_allocation vc = { COMPLETION_INITIALIZER(vc.c), 0 };
313
314         mf_allocate_lp_events(rlp, HvLpEvent_Type_VirtualLan,
315                             sizeof(struct veth_lpevent), number,
316                             &veth_complete_allocation, &vc);
317         wait_for_completion(&vc.c);
318
319         return vc.num;
320 }
321
322 /*
323  * sysfs support
324  */
325
326 struct veth_cnx_attribute {
327         struct attribute attr;
328         ssize_t (*show)(struct veth_lpar_connection *, char *buf);
329         ssize_t (*store)(struct veth_lpar_connection *, const char *buf);
330 };
331
332 static ssize_t veth_cnx_attribute_show(struct kobject *kobj,
333                 struct attribute *attr, char *buf)
334 {
335         struct veth_cnx_attribute *cnx_attr;
336         struct veth_lpar_connection *cnx;
337
338         cnx_attr = container_of(attr, struct veth_cnx_attribute, attr);
339         cnx = container_of(kobj, struct veth_lpar_connection, kobject);
340
341         if (!cnx_attr->show)
342                 return -EIO;
343
344         return cnx_attr->show(cnx, buf);
345 }
346
347 #define CUSTOM_CNX_ATTR(_name, _format, _expression)                    \
348 static ssize_t _name##_show(struct veth_lpar_connection *cnx, char *buf)\
349 {                                                                       \
350         return sprintf(buf, _format, _expression);                      \
351 }                                                                       \
352 struct veth_cnx_attribute veth_cnx_attr_##_name = __ATTR_RO(_name)
353
354 #define SIMPLE_CNX_ATTR(_name)  \
355         CUSTOM_CNX_ATTR(_name, "%lu\n", (unsigned long)cnx->_name)
356
357 SIMPLE_CNX_ATTR(outstanding_tx);
358 SIMPLE_CNX_ATTR(remote_lp);
359 SIMPLE_CNX_ATTR(num_events);
360 SIMPLE_CNX_ATTR(src_inst);
361 SIMPLE_CNX_ATTR(dst_inst);
362 SIMPLE_CNX_ATTR(num_pending_acks);
363 SIMPLE_CNX_ATTR(num_ack_events);
364 CUSTOM_CNX_ATTR(ack_timeout, "%d\n", jiffies_to_msecs(cnx->ack_timeout));
365 CUSTOM_CNX_ATTR(reset_timeout, "%d\n", jiffies_to_msecs(cnx->reset_timeout));
366 CUSTOM_CNX_ATTR(state, "0x%.4lX\n", cnx->state);
367 CUSTOM_CNX_ATTR(last_contact, "%d\n", cnx->last_contact ?
368                 jiffies_to_msecs(jiffies - cnx->last_contact) : 0);
369
370 #define GET_CNX_ATTR(_name)     (&veth_cnx_attr_##_name.attr)
371
372 static struct attribute *veth_cnx_default_attrs[] = {
373         GET_CNX_ATTR(outstanding_tx),
374         GET_CNX_ATTR(remote_lp),
375         GET_CNX_ATTR(num_events),
376         GET_CNX_ATTR(reset_timeout),
377         GET_CNX_ATTR(last_contact),
378         GET_CNX_ATTR(state),
379         GET_CNX_ATTR(src_inst),
380         GET_CNX_ATTR(dst_inst),
381         GET_CNX_ATTR(num_pending_acks),
382         GET_CNX_ATTR(num_ack_events),
383         GET_CNX_ATTR(ack_timeout),
384         NULL
385 };
386
387 static struct sysfs_ops veth_cnx_sysfs_ops = {
388                 .show = veth_cnx_attribute_show
389 };
390
391 static struct kobj_type veth_lpar_connection_ktype = {
392         .release        = veth_release_connection,
393         .sysfs_ops      = &veth_cnx_sysfs_ops,
394         .default_attrs  = veth_cnx_default_attrs
395 };
396
397 struct veth_port_attribute {
398         struct attribute attr;
399         ssize_t (*show)(struct veth_port *, char *buf);
400         ssize_t (*store)(struct veth_port *, const char *buf);
401 };
402
403 static ssize_t veth_port_attribute_show(struct kobject *kobj,
404                 struct attribute *attr, char *buf)
405 {
406         struct veth_port_attribute *port_attr;
407         struct veth_port *port;
408
409         port_attr = container_of(attr, struct veth_port_attribute, attr);
410         port = container_of(kobj, struct veth_port, kobject);
411
412         if (!port_attr->show)
413                 return -EIO;
414
415         return port_attr->show(port, buf);
416 }
417
418 #define CUSTOM_PORT_ATTR(_name, _format, _expression)                   \
419 static ssize_t _name##_show(struct veth_port *port, char *buf)          \
420 {                                                                       \
421         return sprintf(buf, _format, _expression);                      \
422 }                                                                       \
423 struct veth_port_attribute veth_port_attr_##_name = __ATTR_RO(_name)
424
425 #define SIMPLE_PORT_ATTR(_name) \
426         CUSTOM_PORT_ATTR(_name, "%lu\n", (unsigned long)port->_name)
427
428 SIMPLE_PORT_ATTR(promiscuous);
429 SIMPLE_PORT_ATTR(num_mcast);
430 CUSTOM_PORT_ATTR(lpar_map, "0x%X\n", port->lpar_map);
431 CUSTOM_PORT_ATTR(stopped_map, "0x%X\n", port->stopped_map);
432 CUSTOM_PORT_ATTR(mac_addr, "0x%lX\n", port->mac_addr);
433
434 #define GET_PORT_ATTR(_name)    (&veth_port_attr_##_name.attr)
435 static struct attribute *veth_port_default_attrs[] = {
436         GET_PORT_ATTR(mac_addr),
437         GET_PORT_ATTR(lpar_map),
438         GET_PORT_ATTR(stopped_map),
439         GET_PORT_ATTR(promiscuous),
440         GET_PORT_ATTR(num_mcast),
441         NULL
442 };
443
444 static struct sysfs_ops veth_port_sysfs_ops = {
445         .show = veth_port_attribute_show
446 };
447
448 static struct kobj_type veth_port_ktype = {
449         .sysfs_ops      = &veth_port_sysfs_ops,
450         .default_attrs  = veth_port_default_attrs
451 };
452
453 /*
454  * LPAR connection code
455  */
456
457 static inline void veth_kick_statemachine(struct veth_lpar_connection *cnx)
458 {
459         schedule_delayed_work(&cnx->statemachine_wq, 0);
460 }
461
462 static void veth_take_cap(struct veth_lpar_connection *cnx,
463                           struct veth_lpevent *event)
464 {
465         unsigned long flags;
466
467         spin_lock_irqsave(&cnx->lock, flags);
468         /* Receiving caps may mean the other end has just come up, so
469          * we need to reload the instance ID of the far end */
470         cnx->dst_inst =
471                 HvCallEvent_getTargetLpInstanceId(cnx->remote_lp,
472                                                   HvLpEvent_Type_VirtualLan);
473
474         if (cnx->state & VETH_STATE_GOTCAPS) {
475                 veth_error("Received a second capabilities from LPAR %d.\n",
476                            cnx->remote_lp);
477                 event->base_event.xRc = HvLpEvent_Rc_BufferNotAvailable;
478                 HvCallEvent_ackLpEvent((struct HvLpEvent *) event);
479         } else {
480                 memcpy(&cnx->cap_event, event, sizeof(cnx->cap_event));
481                 cnx->state |= VETH_STATE_GOTCAPS;
482                 veth_kick_statemachine(cnx);
483         }
484         spin_unlock_irqrestore(&cnx->lock, flags);
485 }
486
487 static void veth_take_cap_ack(struct veth_lpar_connection *cnx,
488                               struct veth_lpevent *event)
489 {
490         unsigned long flags;
491
492         spin_lock_irqsave(&cnx->lock, flags);
493         if (cnx->state & VETH_STATE_GOTCAPACK) {
494                 veth_error("Received a second capabilities ack from LPAR %d.\n",
495                            cnx->remote_lp);
496         } else {
497                 memcpy(&cnx->cap_ack_event, event,
498                        sizeof(&cnx->cap_ack_event));
499                 cnx->state |= VETH_STATE_GOTCAPACK;
500                 veth_kick_statemachine(cnx);
501         }
502         spin_unlock_irqrestore(&cnx->lock, flags);
503 }
504
505 static void veth_take_monitor_ack(struct veth_lpar_connection *cnx,
506                                   struct veth_lpevent *event)
507 {
508         unsigned long flags;
509
510         spin_lock_irqsave(&cnx->lock, flags);
511         veth_debug("cnx %d: lost connection.\n", cnx->remote_lp);
512
513         /* Avoid kicking the statemachine once we're shutdown.
514          * It's unnecessary and it could break veth_stop_connection(). */
515
516         if (! (cnx->state & VETH_STATE_SHUTDOWN)) {
517                 cnx->state |= VETH_STATE_RESET;
518                 veth_kick_statemachine(cnx);
519         }
520         spin_unlock_irqrestore(&cnx->lock, flags);
521 }
522
523 static void veth_handle_ack(struct veth_lpevent *event)
524 {
525         HvLpIndex rlp = event->base_event.xTargetLp;
526         struct veth_lpar_connection *cnx = veth_cnx[rlp];
527
528         BUG_ON(! cnx);
529
530         switch (event->base_event.xSubtype) {
531         case VETH_EVENT_CAP:
532                 veth_take_cap_ack(cnx, event);
533                 break;
534         case VETH_EVENT_MONITOR:
535                 veth_take_monitor_ack(cnx, event);
536                 break;
537         default:
538                 veth_error("Unknown ack type %d from LPAR %d.\n",
539                                 event->base_event.xSubtype, rlp);
540         };
541 }
542
543 static void veth_handle_int(struct veth_lpevent *event)
544 {
545         HvLpIndex rlp = event->base_event.xSourceLp;
546         struct veth_lpar_connection *cnx = veth_cnx[rlp];
547         unsigned long flags;
548         int i, acked = 0;
549
550         BUG_ON(! cnx);
551
552         switch (event->base_event.xSubtype) {
553         case VETH_EVENT_CAP:
554                 veth_take_cap(cnx, event);
555                 break;
556         case VETH_EVENT_MONITOR:
557                 /* do nothing... this'll hang out here til we're dead,
558                  * and the hypervisor will return it for us. */
559                 break;
560         case VETH_EVENT_FRAMES_ACK:
561                 spin_lock_irqsave(&cnx->lock, flags);
562
563                 for (i = 0; i < VETH_MAX_ACKS_PER_MSG; ++i) {
564                         u16 msgnum = event->u.frames_ack_data.token[i];
565
566                         if (msgnum < VETH_NUMBUFFERS) {
567                                 veth_recycle_msg(cnx, cnx->msgs + msgnum);
568                                 cnx->outstanding_tx--;
569                                 acked++;
570                         }
571                 }
572
573                 if (acked > 0) {
574                         cnx->last_contact = jiffies;
575                         veth_wake_queues(cnx);
576                 }
577
578                 spin_unlock_irqrestore(&cnx->lock, flags);
579                 break;
580         case VETH_EVENT_FRAMES:
581                 veth_receive(cnx, event);
582                 break;
583         default:
584                 veth_error("Unknown interrupt type %d from LPAR %d.\n",
585                                 event->base_event.xSubtype, rlp);
586         };
587 }
588
589 static void veth_handle_event(struct HvLpEvent *event)
590 {
591         struct veth_lpevent *veth_event = (struct veth_lpevent *)event;
592
593         if (hvlpevent_is_ack(event))
594                 veth_handle_ack(veth_event);
595         else
596                 veth_handle_int(veth_event);
597 }
598
599 static int veth_process_caps(struct veth_lpar_connection *cnx)
600 {
601         struct veth_cap_data *remote_caps = &cnx->remote_caps;
602         int num_acks_needed;
603
604         /* Convert timer to jiffies */
605         cnx->ack_timeout = remote_caps->ack_timeout * HZ / 1000000;
606
607         if ( (remote_caps->num_buffers == 0)
608              || (remote_caps->ack_threshold > VETH_MAX_ACKS_PER_MSG)
609              || (remote_caps->ack_threshold == 0)
610              || (cnx->ack_timeout == 0) ) {
611                 veth_error("Received incompatible capabilities from LPAR %d.\n",
612                                 cnx->remote_lp);
613                 return HvLpEvent_Rc_InvalidSubtypeData;
614         }
615
616         num_acks_needed = (remote_caps->num_buffers
617                            / remote_caps->ack_threshold) + 1;
618
619         /* FIXME: locking on num_ack_events? */
620         if (cnx->num_ack_events < num_acks_needed) {
621                 int num;
622
623                 num = veth_allocate_events(cnx->remote_lp,
624                                            num_acks_needed-cnx->num_ack_events);
625                 if (num > 0)
626                         cnx->num_ack_events += num;
627
628                 if (cnx->num_ack_events < num_acks_needed) {
629                         veth_error("Couldn't allocate enough ack events "
630                                         "for LPAR %d.\n", cnx->remote_lp);
631
632                         return HvLpEvent_Rc_BufferNotAvailable;
633                 }
634         }
635
636
637         return HvLpEvent_Rc_Good;
638 }
639
640 /* FIXME: The gotos here are a bit dubious */
641 static void veth_statemachine(struct work_struct *work)
642 {
643         struct veth_lpar_connection *cnx =
644                 container_of(work, struct veth_lpar_connection,
645                              statemachine_wq.work);
646         int rlp = cnx->remote_lp;
647         int rc;
648
649         spin_lock_irq(&cnx->lock);
650
651  restart:
652         if (cnx->state & VETH_STATE_RESET) {
653                 if (cnx->state & VETH_STATE_OPEN)
654                         HvCallEvent_closeLpEventPath(cnx->remote_lp,
655                                                      HvLpEvent_Type_VirtualLan);
656
657                 /*
658                  * Reset ack data. This prevents the ack_timer actually
659                  * doing anything, even if it runs one more time when
660                  * we drop the lock below.
661                  */
662                 memset(&cnx->pending_acks, 0xff, sizeof (cnx->pending_acks));
663                 cnx->num_pending_acks = 0;
664
665                 cnx->state &= ~(VETH_STATE_RESET | VETH_STATE_SENTMON
666                                 | VETH_STATE_OPEN | VETH_STATE_SENTCAPS
667                                 | VETH_STATE_GOTCAPACK | VETH_STATE_GOTCAPS
668                                 | VETH_STATE_SENTCAPACK | VETH_STATE_READY);
669
670                 /* Clean up any leftover messages */
671                 if (cnx->msgs) {
672                         int i;
673                         for (i = 0; i < VETH_NUMBUFFERS; ++i)
674                                 veth_recycle_msg(cnx, cnx->msgs + i);
675                 }
676
677                 cnx->outstanding_tx = 0;
678                 veth_wake_queues(cnx);
679
680                 /* Drop the lock so we can do stuff that might sleep or
681                  * take other locks. */
682                 spin_unlock_irq(&cnx->lock);
683
684                 del_timer_sync(&cnx->ack_timer);
685                 del_timer_sync(&cnx->reset_timer);
686
687                 spin_lock_irq(&cnx->lock);
688
689                 if (cnx->state & VETH_STATE_RESET)
690                         goto restart;
691
692                 /* Hack, wait for the other end to reset itself. */
693                 if (! (cnx->state & VETH_STATE_SHUTDOWN)) {
694                         schedule_delayed_work(&cnx->statemachine_wq, 5 * HZ);
695                         goto out;
696                 }
697         }
698
699         if (cnx->state & VETH_STATE_SHUTDOWN)
700                 /* It's all over, do nothing */
701                 goto out;
702
703         if ( !(cnx->state & VETH_STATE_OPEN) ) {
704                 if (! cnx->msgs || (cnx->num_events < (2 + VETH_NUMBUFFERS)) )
705                         goto cant_cope;
706
707                 HvCallEvent_openLpEventPath(rlp, HvLpEvent_Type_VirtualLan);
708                 cnx->src_inst =
709                         HvCallEvent_getSourceLpInstanceId(rlp,
710                                                           HvLpEvent_Type_VirtualLan);
711                 cnx->dst_inst =
712                         HvCallEvent_getTargetLpInstanceId(rlp,
713                                                           HvLpEvent_Type_VirtualLan);
714                 cnx->state |= VETH_STATE_OPEN;
715         }
716
717         if ( (cnx->state & VETH_STATE_OPEN)
718              && !(cnx->state & VETH_STATE_SENTMON) ) {
719                 rc = veth_signalevent(cnx, VETH_EVENT_MONITOR,
720                                       HvLpEvent_AckInd_DoAck,
721                                       HvLpEvent_AckType_DeferredAck,
722                                       0, 0, 0, 0, 0, 0);
723
724                 if (rc == HvLpEvent_Rc_Good) {
725                         cnx->state |= VETH_STATE_SENTMON;
726                 } else {
727                         if ( (rc != HvLpEvent_Rc_PartitionDead)
728                              && (rc != HvLpEvent_Rc_PathClosed) )
729                                 veth_error("Error sending monitor to LPAR %d, "
730                                                 "rc = %d\n", rlp, rc);
731
732                         /* Oh well, hope we get a cap from the other
733                          * end and do better when that kicks us */
734                         goto out;
735                 }
736         }
737
738         if ( (cnx->state & VETH_STATE_OPEN)
739              && !(cnx->state & VETH_STATE_SENTCAPS)) {
740                 u64 *rawcap = (u64 *)&cnx->local_caps;
741
742                 rc = veth_signalevent(cnx, VETH_EVENT_CAP,
743                                       HvLpEvent_AckInd_DoAck,
744                                       HvLpEvent_AckType_ImmediateAck,
745                                       0, rawcap[0], rawcap[1], rawcap[2],
746                                       rawcap[3], rawcap[4]);
747
748                 if (rc == HvLpEvent_Rc_Good) {
749                         cnx->state |= VETH_STATE_SENTCAPS;
750                 } else {
751                         if ( (rc != HvLpEvent_Rc_PartitionDead)
752                              && (rc != HvLpEvent_Rc_PathClosed) )
753                                 veth_error("Error sending caps to LPAR %d, "
754                                                 "rc = %d\n", rlp, rc);
755
756                         /* Oh well, hope we get a cap from the other
757                          * end and do better when that kicks us */
758                         goto out;
759                 }
760         }
761
762         if ((cnx->state & VETH_STATE_GOTCAPS)
763             && !(cnx->state & VETH_STATE_SENTCAPACK)) {
764                 struct veth_cap_data *remote_caps = &cnx->remote_caps;
765
766                 memcpy(remote_caps, &cnx->cap_event.u.caps_data,
767                        sizeof(*remote_caps));
768
769                 spin_unlock_irq(&cnx->lock);
770                 rc = veth_process_caps(cnx);
771                 spin_lock_irq(&cnx->lock);
772
773                 /* We dropped the lock, so recheck for anything which
774                  * might mess us up */
775                 if (cnx->state & (VETH_STATE_RESET|VETH_STATE_SHUTDOWN))
776                         goto restart;
777
778                 cnx->cap_event.base_event.xRc = rc;
779                 HvCallEvent_ackLpEvent((struct HvLpEvent *)&cnx->cap_event);
780                 if (rc == HvLpEvent_Rc_Good)
781                         cnx->state |= VETH_STATE_SENTCAPACK;
782                 else
783                         goto cant_cope;
784         }
785
786         if ((cnx->state & VETH_STATE_GOTCAPACK)
787             && (cnx->state & VETH_STATE_GOTCAPS)
788             && !(cnx->state & VETH_STATE_READY)) {
789                 if (cnx->cap_ack_event.base_event.xRc == HvLpEvent_Rc_Good) {
790                         /* Start the ACK timer */
791                         cnx->ack_timer.expires = jiffies + cnx->ack_timeout;
792                         add_timer(&cnx->ack_timer);
793                         cnx->state |= VETH_STATE_READY;
794                 } else {
795                         veth_error("Caps rejected by LPAR %d, rc = %d\n",
796                                         rlp, cnx->cap_ack_event.base_event.xRc);
797                         goto cant_cope;
798                 }
799         }
800
801  out:
802         spin_unlock_irq(&cnx->lock);
803         return;
804
805  cant_cope:
806         /* FIXME: we get here if something happens we really can't
807          * cope with.  The link will never work once we get here, and
808          * all we can do is not lock the rest of the system up */
809         veth_error("Unrecoverable error on connection to LPAR %d, shutting down"
810                         " (state = 0x%04lx)\n", rlp, cnx->state);
811         cnx->state |= VETH_STATE_SHUTDOWN;
812         spin_unlock_irq(&cnx->lock);
813 }
814
815 static int veth_init_connection(u8 rlp)
816 {
817         struct veth_lpar_connection *cnx;
818         struct veth_msg *msgs;
819         int i, rc;
820
821         if ( (rlp == this_lp)
822              || ! HvLpConfig_doLpsCommunicateOnVirtualLan(this_lp, rlp) )
823                 return 0;
824
825         cnx = kmalloc(sizeof(*cnx), GFP_KERNEL);
826         if (! cnx)
827                 return -ENOMEM;
828         memset(cnx, 0, sizeof(*cnx));
829
830         cnx->remote_lp = rlp;
831         spin_lock_init(&cnx->lock);
832         INIT_DELAYED_WORK(&cnx->statemachine_wq, veth_statemachine);
833
834         init_timer(&cnx->ack_timer);
835         cnx->ack_timer.function = veth_timed_ack;
836         cnx->ack_timer.data = (unsigned long) cnx;
837
838         init_timer(&cnx->reset_timer);
839         cnx->reset_timer.function = veth_timed_reset;
840         cnx->reset_timer.data = (unsigned long) cnx;
841         cnx->reset_timeout = 5 * HZ * (VETH_ACKTIMEOUT / 1000000);
842
843         memset(&cnx->pending_acks, 0xff, sizeof (cnx->pending_acks));
844
845         veth_cnx[rlp] = cnx;
846
847         /* This gets us 1 reference, which is held on behalf of the driver
848          * infrastructure. It's released at module unload. */
849         kobject_init(&cnx->kobject);
850         cnx->kobject.ktype = &veth_lpar_connection_ktype;
851         rc = kobject_set_name(&cnx->kobject, "cnx%.2d", rlp);
852         if (rc != 0)
853                 return rc;
854
855         msgs = kmalloc(VETH_NUMBUFFERS * sizeof(struct veth_msg), GFP_KERNEL);
856         if (! msgs) {
857                 veth_error("Can't allocate buffers for LPAR %d.\n", rlp);
858                 return -ENOMEM;
859         }
860
861         cnx->msgs = msgs;
862         memset(msgs, 0, VETH_NUMBUFFERS * sizeof(struct veth_msg));
863
864         for (i = 0; i < VETH_NUMBUFFERS; i++) {
865                 msgs[i].token = i;
866                 veth_stack_push(cnx, msgs + i);
867         }
868
869         cnx->num_events = veth_allocate_events(rlp, 2 + VETH_NUMBUFFERS);
870
871         if (cnx->num_events < (2 + VETH_NUMBUFFERS)) {
872                 veth_error("Can't allocate enough events for LPAR %d.\n", rlp);
873                 return -ENOMEM;
874         }
875
876         cnx->local_caps.num_buffers = VETH_NUMBUFFERS;
877         cnx->local_caps.ack_threshold = ACK_THRESHOLD;
878         cnx->local_caps.ack_timeout = VETH_ACKTIMEOUT;
879
880         return 0;
881 }
882
883 static void veth_stop_connection(struct veth_lpar_connection *cnx)
884 {
885         if (!cnx)
886                 return;
887
888         spin_lock_irq(&cnx->lock);
889         cnx->state |= VETH_STATE_RESET | VETH_STATE_SHUTDOWN;
890         veth_kick_statemachine(cnx);
891         spin_unlock_irq(&cnx->lock);
892
893         /* There's a slim chance the reset code has just queued the
894          * statemachine to run in five seconds. If so we need to cancel
895          * that and requeue the work to run now. */
896         if (cancel_delayed_work(&cnx->statemachine_wq)) {
897                 spin_lock_irq(&cnx->lock);
898                 veth_kick_statemachine(cnx);
899                 spin_unlock_irq(&cnx->lock);
900         }
901
902         /* Wait for the state machine to run. */
903         flush_scheduled_work();
904 }
905
906 static void veth_destroy_connection(struct veth_lpar_connection *cnx)
907 {
908         if (!cnx)
909                 return;
910
911         if (cnx->num_events > 0)
912                 mf_deallocate_lp_events(cnx->remote_lp,
913                                       HvLpEvent_Type_VirtualLan,
914                                       cnx->num_events,
915                                       NULL, NULL);
916         if (cnx->num_ack_events > 0)
917                 mf_deallocate_lp_events(cnx->remote_lp,
918                                       HvLpEvent_Type_VirtualLan,
919                                       cnx->num_ack_events,
920                                       NULL, NULL);
921
922         kfree(cnx->msgs);
923         veth_cnx[cnx->remote_lp] = NULL;
924         kfree(cnx);
925 }
926
927 static void veth_release_connection(struct kobject *kobj)
928 {
929         struct veth_lpar_connection *cnx;
930         cnx = container_of(kobj, struct veth_lpar_connection, kobject);
931         veth_stop_connection(cnx);
932         veth_destroy_connection(cnx);
933 }
934
935 /*
936  * net_device code
937  */
938
939 static int veth_open(struct net_device *dev)
940 {
941         struct veth_port *port = (struct veth_port *) dev->priv;
942
943         memset(&port->stats, 0, sizeof (port->stats));
944         netif_start_queue(dev);
945         return 0;
946 }
947
948 static int veth_close(struct net_device *dev)
949 {
950         netif_stop_queue(dev);
951         return 0;
952 }
953
954 static struct net_device_stats *veth_get_stats(struct net_device *dev)
955 {
956         struct veth_port *port = (struct veth_port *) dev->priv;
957
958         return &port->stats;
959 }
960
961 static int veth_change_mtu(struct net_device *dev, int new_mtu)
962 {
963         if ((new_mtu < 68) || (new_mtu > VETH_MAX_MTU))
964                 return -EINVAL;
965         dev->mtu = new_mtu;
966         return 0;
967 }
968
969 static void veth_set_multicast_list(struct net_device *dev)
970 {
971         struct veth_port *port = (struct veth_port *) dev->priv;
972         unsigned long flags;
973
974         write_lock_irqsave(&port->mcast_gate, flags);
975
976         if ((dev->flags & IFF_PROMISC) || (dev->flags & IFF_ALLMULTI) ||
977                         (dev->mc_count > VETH_MAX_MCAST)) {
978                 port->promiscuous = 1;
979         } else {
980                 struct dev_mc_list *dmi = dev->mc_list;
981                 int i;
982
983                 port->promiscuous = 0;
984
985                 /* Update table */
986                 port->num_mcast = 0;
987
988                 for (i = 0; i < dev->mc_count; i++) {
989                         u8 *addr = dmi->dmi_addr;
990                         u64 xaddr = 0;
991
992                         if (addr[0] & 0x01) {/* multicast address? */
993                                 memcpy(&xaddr, addr, ETH_ALEN);
994                                 port->mcast_addr[port->num_mcast] = xaddr;
995                                 port->num_mcast++;
996                         }
997                         dmi = dmi->next;
998                 }
999         }
1000
1001         write_unlock_irqrestore(&port->mcast_gate, flags);
1002 }
1003
1004 static void veth_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
1005 {
1006         strncpy(info->driver, DRV_NAME, sizeof(info->driver) - 1);
1007         info->driver[sizeof(info->driver) - 1] = '\0';
1008         strncpy(info->version, DRV_VERSION, sizeof(info->version) - 1);
1009         info->version[sizeof(info->version) - 1] = '\0';
1010 }
1011
1012 static int veth_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
1013 {
1014         ecmd->supported = (SUPPORTED_1000baseT_Full
1015                           | SUPPORTED_Autoneg | SUPPORTED_FIBRE);
1016         ecmd->advertising = (SUPPORTED_1000baseT_Full
1017                             | SUPPORTED_Autoneg | SUPPORTED_FIBRE);
1018         ecmd->port = PORT_FIBRE;
1019         ecmd->transceiver = XCVR_INTERNAL;
1020         ecmd->phy_address = 0;
1021         ecmd->speed = SPEED_1000;
1022         ecmd->duplex = DUPLEX_FULL;
1023         ecmd->autoneg = AUTONEG_ENABLE;
1024         ecmd->maxtxpkt = 120;
1025         ecmd->maxrxpkt = 120;
1026         return 0;
1027 }
1028
1029 static u32 veth_get_link(struct net_device *dev)
1030 {
1031         return 1;
1032 }
1033
1034 static const struct ethtool_ops ops = {
1035         .get_drvinfo = veth_get_drvinfo,
1036         .get_settings = veth_get_settings,
1037         .get_link = veth_get_link,
1038 };
1039
1040 static struct net_device * __init veth_probe_one(int vlan,
1041                 struct vio_dev *vio_dev)
1042 {
1043         struct net_device *dev;
1044         struct veth_port *port;
1045         struct device *vdev = &vio_dev->dev;
1046         int i, rc;
1047         const unsigned char *mac_addr;
1048
1049         mac_addr = vio_get_attribute(vio_dev, "local-mac-address", NULL);
1050         if (mac_addr == NULL)
1051                 mac_addr = vio_get_attribute(vio_dev, "mac-address", NULL);
1052         if (mac_addr == NULL) {
1053                 veth_error("Unable to fetch MAC address from device tree.\n");
1054                 return NULL;
1055         }
1056
1057         dev = alloc_etherdev(sizeof (struct veth_port));
1058         if (! dev) {
1059                 veth_error("Unable to allocate net_device structure!\n");
1060                 return NULL;
1061         }
1062
1063         port = (struct veth_port *) dev->priv;
1064
1065         spin_lock_init(&port->queue_lock);
1066         rwlock_init(&port->mcast_gate);
1067         port->stopped_map = 0;
1068
1069         for (i = 0; i < HVMAXARCHITECTEDLPS; i++) {
1070                 HvLpVirtualLanIndexMap map;
1071
1072                 if (i == this_lp)
1073                         continue;
1074                 map = HvLpConfig_getVirtualLanIndexMapForLp(i);
1075                 if (map & (0x8000 >> vlan))
1076                         port->lpar_map |= (1 << i);
1077         }
1078         port->dev = vdev;
1079
1080         memcpy(dev->dev_addr, mac_addr, ETH_ALEN);
1081
1082         dev->mtu = VETH_MAX_MTU;
1083
1084         memcpy(&port->mac_addr, mac_addr, ETH_ALEN);
1085
1086         dev->open = veth_open;
1087         dev->hard_start_xmit = veth_start_xmit;
1088         dev->stop = veth_close;
1089         dev->get_stats = veth_get_stats;
1090         dev->change_mtu = veth_change_mtu;
1091         dev->set_mac_address = NULL;
1092         dev->set_multicast_list = veth_set_multicast_list;
1093         SET_ETHTOOL_OPS(dev, &ops);
1094
1095         SET_NETDEV_DEV(dev, vdev);
1096
1097         rc = register_netdev(dev);
1098         if (rc != 0) {
1099                 veth_error("Failed registering net device for vlan%d.\n", vlan);
1100                 free_netdev(dev);
1101                 return NULL;
1102         }
1103
1104         kobject_init(&port->kobject);
1105         port->kobject.parent = &dev->class_dev.kobj;
1106         port->kobject.ktype  = &veth_port_ktype;
1107         kobject_set_name(&port->kobject, "veth_port");
1108         if (0 != kobject_add(&port->kobject))
1109                 veth_error("Failed adding port for %s to sysfs.\n", dev->name);
1110
1111         veth_info("%s attached to iSeries vlan %d (LPAR map = 0x%.4X)\n",
1112                         dev->name, vlan, port->lpar_map);
1113
1114         return dev;
1115 }
1116
1117 /*
1118  * Tx path
1119  */
1120
1121 static int veth_transmit_to_one(struct sk_buff *skb, HvLpIndex rlp,
1122                                 struct net_device *dev)
1123 {
1124         struct veth_lpar_connection *cnx = veth_cnx[rlp];
1125         struct veth_port *port = (struct veth_port *) dev->priv;
1126         HvLpEvent_Rc rc;
1127         struct veth_msg *msg = NULL;
1128         unsigned long flags;
1129
1130         if (! cnx)
1131                 return 0;
1132
1133         spin_lock_irqsave(&cnx->lock, flags);
1134
1135         if (! (cnx->state & VETH_STATE_READY))
1136                 goto no_error;
1137
1138         if ((skb->len - ETH_HLEN) > VETH_MAX_MTU)
1139                 goto drop;
1140
1141         msg = veth_stack_pop(cnx);
1142         if (! msg)
1143                 goto drop;
1144
1145         msg->in_use = 1;
1146         msg->skb = skb_get(skb);
1147
1148         msg->data.addr[0] = dma_map_single(port->dev, skb->data,
1149                                 skb->len, DMA_TO_DEVICE);
1150
1151         if (dma_mapping_error(msg->data.addr[0]))
1152                 goto recycle_and_drop;
1153
1154         msg->dev = port->dev;
1155         msg->data.len[0] = skb->len;
1156         msg->data.eofmask = 1 << VETH_EOF_SHIFT;
1157
1158         rc = veth_signaldata(cnx, VETH_EVENT_FRAMES, msg->token, &msg->data);
1159
1160         if (rc != HvLpEvent_Rc_Good)
1161                 goto recycle_and_drop;
1162
1163         /* If the timer's not already running, start it now. */
1164         if (0 == cnx->outstanding_tx)
1165                 mod_timer(&cnx->reset_timer, jiffies + cnx->reset_timeout);
1166
1167         cnx->last_contact = jiffies;
1168         cnx->outstanding_tx++;
1169
1170         if (veth_stack_is_empty(cnx))
1171                 veth_stop_queues(cnx);
1172
1173  no_error:
1174         spin_unlock_irqrestore(&cnx->lock, flags);
1175         return 0;
1176
1177  recycle_and_drop:
1178         veth_recycle_msg(cnx, msg);
1179  drop:
1180         spin_unlock_irqrestore(&cnx->lock, flags);
1181         return 1;
1182 }
1183
1184 static void veth_transmit_to_many(struct sk_buff *skb,
1185                                           HvLpIndexMap lpmask,
1186                                           struct net_device *dev)
1187 {
1188         struct veth_port *port = (struct veth_port *) dev->priv;
1189         int i, success, error;
1190
1191         success = error = 0;
1192
1193         for (i = 0; i < HVMAXARCHITECTEDLPS; i++) {
1194                 if ((lpmask & (1 << i)) == 0)
1195                         continue;
1196
1197                 if (veth_transmit_to_one(skb, i, dev))
1198                         error = 1;
1199                 else
1200                         success = 1;
1201         }
1202
1203         if (error)
1204                 port->stats.tx_errors++;
1205
1206         if (success) {
1207                 port->stats.tx_packets++;
1208                 port->stats.tx_bytes += skb->len;
1209         }
1210 }
1211
1212 static int veth_start_xmit(struct sk_buff *skb, struct net_device *dev)
1213 {
1214         unsigned char *frame = skb->data;
1215         struct veth_port *port = (struct veth_port *) dev->priv;
1216         HvLpIndexMap lpmask;
1217
1218         if (! (frame[0] & 0x01)) {
1219                 /* unicast packet */
1220                 HvLpIndex rlp = frame[5];
1221
1222                 if ( ! ((1 << rlp) & port->lpar_map) ) {
1223                         dev_kfree_skb(skb);
1224                         return 0;
1225                 }
1226
1227                 lpmask = 1 << rlp;
1228         } else {
1229                 lpmask = port->lpar_map;
1230         }
1231
1232         veth_transmit_to_many(skb, lpmask, dev);
1233
1234         dev_kfree_skb(skb);
1235
1236         return 0;
1237 }
1238
1239 /* You must hold the connection's lock when you call this function. */
1240 static void veth_recycle_msg(struct veth_lpar_connection *cnx,
1241                              struct veth_msg *msg)
1242 {
1243         u32 dma_address, dma_length;
1244
1245         if (msg->in_use) {
1246                 msg->in_use = 0;
1247                 dma_address = msg->data.addr[0];
1248                 dma_length = msg->data.len[0];
1249
1250                 if (!dma_mapping_error(dma_address))
1251                         dma_unmap_single(msg->dev, dma_address, dma_length,
1252                                         DMA_TO_DEVICE);
1253
1254                 if (msg->skb) {
1255                         dev_kfree_skb_any(msg->skb);
1256                         msg->skb = NULL;
1257                 }
1258
1259                 memset(&msg->data, 0, sizeof(msg->data));
1260                 veth_stack_push(cnx, msg);
1261         } else if (cnx->state & VETH_STATE_OPEN) {
1262                 veth_error("Non-pending frame (# %d) acked by LPAR %d.\n",
1263                                 cnx->remote_lp, msg->token);
1264         }
1265 }
1266
1267 static void veth_wake_queues(struct veth_lpar_connection *cnx)
1268 {
1269         int i;
1270
1271         for (i = 0; i < HVMAXARCHITECTEDVIRTUALLANS; i++) {
1272                 struct net_device *dev = veth_dev[i];
1273                 struct veth_port *port;
1274                 unsigned long flags;
1275
1276                 if (! dev)
1277                         continue;
1278
1279                 port = (struct veth_port *)dev->priv;
1280
1281                 if (! (port->lpar_map & (1<<cnx->remote_lp)))
1282                         continue;
1283
1284                 spin_lock_irqsave(&port->queue_lock, flags);
1285
1286                 port->stopped_map &= ~(1 << cnx->remote_lp);
1287
1288                 if (0 == port->stopped_map && netif_queue_stopped(dev)) {
1289                         veth_debug("cnx %d: woke queue for %s.\n",
1290                                         cnx->remote_lp, dev->name);
1291                         netif_wake_queue(dev);
1292                 }
1293                 spin_unlock_irqrestore(&port->queue_lock, flags);
1294         }
1295 }
1296
1297 static void veth_stop_queues(struct veth_lpar_connection *cnx)
1298 {
1299         int i;
1300
1301         for (i = 0; i < HVMAXARCHITECTEDVIRTUALLANS; i++) {
1302                 struct net_device *dev = veth_dev[i];
1303                 struct veth_port *port;
1304
1305                 if (! dev)
1306                         continue;
1307
1308                 port = (struct veth_port *)dev->priv;
1309
1310                 /* If this cnx is not on the vlan for this port, continue */
1311                 if (! (port->lpar_map & (1 << cnx->remote_lp)))
1312                         continue;
1313
1314                 spin_lock(&port->queue_lock);
1315
1316                 netif_stop_queue(dev);
1317                 port->stopped_map |= (1 << cnx->remote_lp);
1318
1319                 veth_debug("cnx %d: stopped queue for %s, map = 0x%x.\n",
1320                                 cnx->remote_lp, dev->name, port->stopped_map);
1321
1322                 spin_unlock(&port->queue_lock);
1323         }
1324 }
1325
1326 static void veth_timed_reset(unsigned long ptr)
1327 {
1328         struct veth_lpar_connection *cnx = (struct veth_lpar_connection *)ptr;
1329         unsigned long trigger_time, flags;
1330
1331         /* FIXME is it possible this fires after veth_stop_connection()?
1332          * That would reschedule the statemachine for 5 seconds and probably
1333          * execute it after the module's been unloaded. Hmm. */
1334
1335         spin_lock_irqsave(&cnx->lock, flags);
1336
1337         if (cnx->outstanding_tx > 0) {
1338                 trigger_time = cnx->last_contact + cnx->reset_timeout;
1339
1340                 if (trigger_time < jiffies) {
1341                         cnx->state |= VETH_STATE_RESET;
1342                         veth_kick_statemachine(cnx);
1343                         veth_error("%d packets not acked by LPAR %d within %d "
1344                                         "seconds, resetting.\n",
1345                                         cnx->outstanding_tx, cnx->remote_lp,
1346                                         cnx->reset_timeout / HZ);
1347                 } else {
1348                         /* Reschedule the timer */
1349                         trigger_time = jiffies + cnx->reset_timeout;
1350                         mod_timer(&cnx->reset_timer, trigger_time);
1351                 }
1352         }
1353
1354         spin_unlock_irqrestore(&cnx->lock, flags);
1355 }
1356
1357 /*
1358  * Rx path
1359  */
1360
1361 static inline int veth_frame_wanted(struct veth_port *port, u64 mac_addr)
1362 {
1363         int wanted = 0;
1364         int i;
1365         unsigned long flags;
1366
1367         if ( (mac_addr == port->mac_addr) || (mac_addr == 0xffffffffffff0000) )
1368                 return 1;
1369
1370         read_lock_irqsave(&port->mcast_gate, flags);
1371
1372         if (port->promiscuous) {
1373                 wanted = 1;
1374                 goto out;
1375         }
1376
1377         for (i = 0; i < port->num_mcast; ++i) {
1378                 if (port->mcast_addr[i] == mac_addr) {
1379                         wanted = 1;
1380                         break;
1381                 }
1382         }
1383
1384  out:
1385         read_unlock_irqrestore(&port->mcast_gate, flags);
1386
1387         return wanted;
1388 }
1389
1390 struct dma_chunk {
1391         u64 addr;
1392         u64 size;
1393 };
1394
1395 #define VETH_MAX_PAGES_PER_FRAME ( (VETH_MAX_MTU+PAGE_SIZE-2)/PAGE_SIZE + 1 )
1396
1397 static inline void veth_build_dma_list(struct dma_chunk *list,
1398                                        unsigned char *p, unsigned long length)
1399 {
1400         unsigned long done;
1401         int i = 1;
1402
1403         /* FIXME: skbs are continguous in real addresses.  Do we
1404          * really need to break it into PAGE_SIZE chunks, or can we do
1405          * it just at the granularity of iSeries real->absolute
1406          * mapping?  Indeed, given the way the allocator works, can we
1407          * count on them being absolutely contiguous? */
1408         list[0].addr = iseries_hv_addr(p);
1409         list[0].size = min(length,
1410                            PAGE_SIZE - ((unsigned long)p & ~PAGE_MASK));
1411
1412         done = list[0].size;
1413         while (done < length) {
1414                 list[i].addr = iseries_hv_addr(p + done);
1415                 list[i].size = min(length-done, PAGE_SIZE);
1416                 done += list[i].size;
1417                 i++;
1418         }
1419 }
1420
1421 static void veth_flush_acks(struct veth_lpar_connection *cnx)
1422 {
1423         HvLpEvent_Rc rc;
1424
1425         rc = veth_signaldata(cnx, VETH_EVENT_FRAMES_ACK,
1426                              0, &cnx->pending_acks);
1427
1428         if (rc != HvLpEvent_Rc_Good)
1429                 veth_error("Failed acking frames from LPAR %d, rc = %d\n",
1430                                 cnx->remote_lp, (int)rc);
1431
1432         cnx->num_pending_acks = 0;
1433         memset(&cnx->pending_acks, 0xff, sizeof(cnx->pending_acks));
1434 }
1435
1436 static void veth_receive(struct veth_lpar_connection *cnx,
1437                          struct veth_lpevent *event)
1438 {
1439         struct veth_frames_data *senddata = &event->u.frames_data;
1440         int startchunk = 0;
1441         int nchunks;
1442         unsigned long flags;
1443         HvLpDma_Rc rc;
1444
1445         do {
1446                 u16 length = 0;
1447                 struct sk_buff *skb;
1448                 struct dma_chunk local_list[VETH_MAX_PAGES_PER_FRAME];
1449                 struct dma_chunk remote_list[VETH_MAX_FRAMES_PER_MSG];
1450                 u64 dest;
1451                 HvLpVirtualLanIndex vlan;
1452                 struct net_device *dev;
1453                 struct veth_port *port;
1454
1455                 /* FIXME: do we need this? */
1456                 memset(local_list, 0, sizeof(local_list));
1457                 memset(remote_list, 0, sizeof(VETH_MAX_FRAMES_PER_MSG));
1458
1459                 /* a 0 address marks the end of the valid entries */
1460                 if (senddata->addr[startchunk] == 0)
1461                         break;
1462
1463                 /* make sure that we have at least 1 EOF entry in the
1464                  * remaining entries */
1465                 if (! (senddata->eofmask >> (startchunk + VETH_EOF_SHIFT))) {
1466                         veth_error("Missing EOF fragment in event "
1467                                         "eofmask = 0x%x startchunk = %d\n",
1468                                         (unsigned)senddata->eofmask,
1469                                         startchunk);
1470                         break;
1471                 }
1472
1473                 /* build list of chunks in this frame */
1474                 nchunks = 0;
1475                 do {
1476                         remote_list[nchunks].addr =
1477                                 (u64) senddata->addr[startchunk+nchunks] << 32;
1478                         remote_list[nchunks].size =
1479                                 senddata->len[startchunk+nchunks];
1480                         length += remote_list[nchunks].size;
1481                 } while (! (senddata->eofmask &
1482                             (1 << (VETH_EOF_SHIFT + startchunk + nchunks++))));
1483
1484                 /* length == total length of all chunks */
1485                 /* nchunks == # of chunks in this frame */
1486
1487                 if ((length - ETH_HLEN) > VETH_MAX_MTU) {
1488                         veth_error("Received oversize frame from LPAR %d "
1489                                         "(length = %d)\n",
1490                                         cnx->remote_lp, length);
1491                         continue;
1492                 }
1493
1494                 skb = alloc_skb(length, GFP_ATOMIC);
1495                 if (!skb)
1496                         continue;
1497
1498                 veth_build_dma_list(local_list, skb->data, length);
1499
1500                 rc = HvCallEvent_dmaBufList(HvLpEvent_Type_VirtualLan,
1501                                             event->base_event.xSourceLp,
1502                                             HvLpDma_Direction_RemoteToLocal,
1503                                             cnx->src_inst,
1504                                             cnx->dst_inst,
1505                                             HvLpDma_AddressType_RealAddress,
1506                                             HvLpDma_AddressType_TceIndex,
1507                                             iseries_hv_addr(&local_list),
1508                                             iseries_hv_addr(&remote_list),
1509                                             length);
1510                 if (rc != HvLpDma_Rc_Good) {
1511                         dev_kfree_skb_irq(skb);
1512                         continue;
1513                 }
1514
1515                 vlan = skb->data[9];
1516                 dev = veth_dev[vlan];
1517                 if (! dev) {
1518                         /*
1519                          * Some earlier versions of the driver sent
1520                          * broadcasts down all connections, even to lpars
1521                          * that weren't on the relevant vlan. So ignore
1522                          * packets belonging to a vlan we're not on.
1523                          * We can also be here if we receive packets while
1524                          * the driver is going down, because then dev is NULL.
1525                          */
1526                         dev_kfree_skb_irq(skb);
1527                         continue;
1528                 }
1529
1530                 port = (struct veth_port *)dev->priv;
1531                 dest = *((u64 *) skb->data) & 0xFFFFFFFFFFFF0000;
1532
1533                 if ((vlan > HVMAXARCHITECTEDVIRTUALLANS) || !port) {
1534                         dev_kfree_skb_irq(skb);
1535                         continue;
1536                 }
1537                 if (! veth_frame_wanted(port, dest)) {
1538                         dev_kfree_skb_irq(skb);
1539                         continue;
1540                 }
1541
1542                 skb_put(skb, length);
1543                 skb->dev = dev;
1544                 skb->protocol = eth_type_trans(skb, dev);
1545                 skb->ip_summed = CHECKSUM_NONE;
1546                 netif_rx(skb);  /* send it up */
1547                 port->stats.rx_packets++;
1548                 port->stats.rx_bytes += length;
1549         } while (startchunk += nchunks, startchunk < VETH_MAX_FRAMES_PER_MSG);
1550
1551         /* Ack it */
1552         spin_lock_irqsave(&cnx->lock, flags);
1553         BUG_ON(cnx->num_pending_acks > VETH_MAX_ACKS_PER_MSG);
1554
1555         cnx->pending_acks[cnx->num_pending_acks++] =
1556                 event->base_event.xCorrelationToken;
1557
1558         if ( (cnx->num_pending_acks >= cnx->remote_caps.ack_threshold)
1559              || (cnx->num_pending_acks >= VETH_MAX_ACKS_PER_MSG) )
1560                 veth_flush_acks(cnx);
1561
1562         spin_unlock_irqrestore(&cnx->lock, flags);
1563 }
1564
1565 static void veth_timed_ack(unsigned long ptr)
1566 {
1567         struct veth_lpar_connection *cnx = (struct veth_lpar_connection *) ptr;
1568         unsigned long flags;
1569
1570         /* Ack all the events */
1571         spin_lock_irqsave(&cnx->lock, flags);
1572         if (cnx->num_pending_acks > 0)
1573                 veth_flush_acks(cnx);
1574
1575         /* Reschedule the timer */
1576         cnx->ack_timer.expires = jiffies + cnx->ack_timeout;
1577         add_timer(&cnx->ack_timer);
1578         spin_unlock_irqrestore(&cnx->lock, flags);
1579 }
1580
1581 static int veth_remove(struct vio_dev *vdev)
1582 {
1583         struct veth_lpar_connection *cnx;
1584         struct net_device *dev;
1585         struct veth_port *port;
1586         int i;
1587
1588         dev = veth_dev[vdev->unit_address];
1589
1590         if (! dev)
1591                 return 0;
1592
1593         port = netdev_priv(dev);
1594
1595         for (i = 0; i < HVMAXARCHITECTEDLPS; i++) {
1596                 cnx = veth_cnx[i];
1597
1598                 if (cnx && (port->lpar_map & (1 << i))) {
1599                         /* Drop our reference to connections on our VLAN */
1600                         kobject_put(&cnx->kobject);
1601                 }
1602         }
1603
1604         veth_dev[vdev->unit_address] = NULL;
1605         kobject_del(&port->kobject);
1606         kobject_put(&port->kobject);
1607         unregister_netdev(dev);
1608         free_netdev(dev);
1609
1610         return 0;
1611 }
1612
1613 static int veth_probe(struct vio_dev *vdev, const struct vio_device_id *id)
1614 {
1615         int i = vdev->unit_address;
1616         struct net_device *dev;
1617         struct veth_port *port;
1618
1619         dev = veth_probe_one(i, vdev);
1620         if (dev == NULL) {
1621                 veth_remove(vdev);
1622                 return 1;
1623         }
1624         veth_dev[i] = dev;
1625
1626         port = (struct veth_port*)netdev_priv(dev);
1627
1628         /* Start the state machine on each connection on this vlan. If we're
1629          * the first dev to do so this will commence link negotiation */
1630         for (i = 0; i < HVMAXARCHITECTEDLPS; i++) {
1631                 struct veth_lpar_connection *cnx;
1632
1633                 if (! (port->lpar_map & (1 << i)))
1634                         continue;
1635
1636                 cnx = veth_cnx[i];
1637                 if (!cnx)
1638                         continue;
1639
1640                 kobject_get(&cnx->kobject);
1641                 veth_kick_statemachine(cnx);
1642         }
1643
1644         return 0;
1645 }
1646
1647 /**
1648  * veth_device_table: Used by vio.c to match devices that we
1649  * support.
1650  */
1651 static struct vio_device_id veth_device_table[] __devinitdata = {
1652         { "network", "IBM,iSeries-l-lan" },
1653         { "", "" }
1654 };
1655 MODULE_DEVICE_TABLE(vio, veth_device_table);
1656
1657 static struct vio_driver veth_driver = {
1658         .id_table = veth_device_table,
1659         .probe = veth_probe,
1660         .remove = veth_remove,
1661         .driver = {
1662                 .name = DRV_NAME,
1663                 .owner = THIS_MODULE,
1664         }
1665 };
1666
1667 /*
1668  * Module initialization/cleanup
1669  */
1670
1671 void __exit veth_module_cleanup(void)
1672 {
1673         int i;
1674         struct veth_lpar_connection *cnx;
1675
1676         /* Disconnect our "irq" to stop events coming from the Hypervisor. */
1677         HvLpEvent_unregisterHandler(HvLpEvent_Type_VirtualLan);
1678
1679         /* Make sure any work queued from Hypervisor callbacks is finished. */
1680         flush_scheduled_work();
1681
1682         for (i = 0; i < HVMAXARCHITECTEDLPS; ++i) {
1683                 cnx = veth_cnx[i];
1684
1685                 if (!cnx)
1686                         continue;
1687
1688                 /* Remove the connection from sysfs */
1689                 kobject_del(&cnx->kobject);
1690                 /* Drop the driver's reference to the connection */
1691                 kobject_put(&cnx->kobject);
1692         }
1693
1694         /* Unregister the driver, which will close all the netdevs and stop
1695          * the connections when they're no longer referenced. */
1696         vio_unregister_driver(&veth_driver);
1697 }
1698 module_exit(veth_module_cleanup);
1699
1700 int __init veth_module_init(void)
1701 {
1702         int i;
1703         int rc;
1704
1705         this_lp = HvLpConfig_getLpIndex_outline();
1706
1707         for (i = 0; i < HVMAXARCHITECTEDLPS; ++i) {
1708                 rc = veth_init_connection(i);
1709                 if (rc != 0)
1710                         goto error;
1711         }
1712
1713         HvLpEvent_registerHandler(HvLpEvent_Type_VirtualLan,
1714                                   &veth_handle_event);
1715
1716         rc = vio_register_driver(&veth_driver);
1717         if (rc != 0)
1718                 goto error;
1719
1720         for (i = 0; i < HVMAXARCHITECTEDLPS; ++i) {
1721                 struct kobject *kobj;
1722
1723                 if (!veth_cnx[i])
1724                         continue;
1725
1726                 kobj = &veth_cnx[i]->kobject;
1727                 kobj->parent = &veth_driver.driver.kobj;
1728                 /* If the add failes, complain but otherwise continue */
1729                 if (0 != kobject_add(kobj))
1730                         veth_error("cnx %d: Failed adding to sysfs.\n", i);
1731         }
1732
1733         return 0;
1734
1735 error:
1736         for (i = 0; i < HVMAXARCHITECTEDLPS; ++i) {
1737                 veth_destroy_connection(veth_cnx[i]);
1738         }
1739
1740         return rc;
1741 }
1742 module_init(veth_module_init);