This commit was manufactured by cvs2svn to create branch 'vserver'.
[linux-2.6.git] / drivers / char / hvsi.c
1 /*
2  * Copyright (C) 2004 Hollis Blanchard <hollisb@us.ibm.com>, IBM
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17  */
18
19 /* Host Virtual Serial Interface (HVSI) is a protocol between the hosted OS
20  * and the service processor on IBM pSeries servers. On these servers, there
21  * are no serial ports under the OS's control, and sometimes there is no other
22  * console available either. However, the service processor has two standard
23  * serial ports, so this over-complicated protocol allows the OS to control
24  * those ports by proxy.
25  *
26  * Besides data, the procotol supports the reading/writing of the serial
27  * port's DTR line, and the reading of the CD line. This is to allow the OS to
28  * control a modem attached to the service processor's serial port. Note that
29  * the OS cannot change the speed of the port through this protocol.
30  */
31
32 /* TODO:
33  * test FSP reset
34  * add udbg support for xmon/kdb
35  */
36
37 #undef DEBUG
38
39 #include <linux/console.h>
40 #include <linux/ctype.h>
41 #include <linux/delay.h>
42 #include <linux/init.h>
43 #include <linux/interrupt.h>
44 #include <linux/module.h>
45 #include <linux/major.h>
46 #include <linux/kernel.h>
47 #include <linux/sched.h>
48 #include <linux/spinlock.h>
49 #include <linux/sysrq.h>
50 #include <linux/tty.h>
51 #include <linux/tty_flip.h>
52 #include <asm/hvcall.h>
53 #include <asm/hvconsole.h>
54 #include <asm/prom.h>
55 #include <asm/uaccess.h>
56 #include <asm/vio.h>
57
58 #define HVSI_MAJOR      229
59 #define HVSI_MINOR      128
60 #define MAX_NR_HVSI_CONSOLES 4
61
62 #define HVSI_TIMEOUT (5*HZ)
63 #define HVSI_VERSION 1
64 #define HVSI_MAX_PACKET 256
65 #define HVSI_MAX_READ 16
66 #define HVSI_MAX_OUTGOING_DATA 12
67 #define N_OUTBUF 12
68
69 /*
70  * we pass data via two 8-byte registers, so we would like our char arrays
71  * properly aligned for those loads.
72  */
73 #define __ALIGNED__     __attribute__((__aligned__(sizeof(long))))
74
75 struct hvsi_struct {
76         struct work_struct writer;
77         wait_queue_head_t emptyq; /* woken when outbuf is emptied */
78         wait_queue_head_t stateq; /* woken when HVSI state changes */
79         spinlock_t lock;
80         int index;
81         struct tty_struct *tty;
82         unsigned int count;
83         uint8_t throttle_buf[128];
84         uint8_t outbuf[N_OUTBUF]; /* to implement write_room and chars_in_buffer */
85         /* inbuf is for packet reassembly. leave a little room for leftovers. */
86         uint8_t inbuf[HVSI_MAX_PACKET + HVSI_MAX_READ];
87         uint8_t *inbuf_end;
88         int n_throttle;
89         int n_outbuf;
90         uint32_t vtermno;
91         uint32_t virq;
92         atomic_t seqno; /* HVSI packet sequence number */
93         uint16_t mctrl;
94         uint8_t state;  /* HVSI protocol state */
95         uint8_t flags;
96 #ifdef CONFIG_MAGIC_SYSRQ
97         uint8_t sysrq;
98 #endif /* CONFIG_MAGIC_SYSRQ */
99 };
100 static struct hvsi_struct hvsi_ports[MAX_NR_HVSI_CONSOLES];
101
102 static struct tty_driver *hvsi_driver;
103 static int hvsi_count;
104 static int (*hvsi_wait)(struct hvsi_struct *hp, int state);
105
106 enum HVSI_PROTOCOL_STATE {
107         HVSI_CLOSED,
108         HVSI_WAIT_FOR_VER_RESPONSE,
109         HVSI_WAIT_FOR_VER_QUERY,
110         HVSI_OPEN,
111         HVSI_WAIT_FOR_MCTRL_RESPONSE,
112 };
113 #define HVSI_CONSOLE 0x1
114
115 #define VS_DATA_PACKET_HEADER           0xff
116 #define VS_CONTROL_PACKET_HEADER        0xfe
117 #define VS_QUERY_PACKET_HEADER          0xfd
118 #define VS_QUERY_RESPONSE_PACKET_HEADER 0xfc
119
120 /* control verbs */
121 #define VSV_SET_MODEM_CTL    1 /* to service processor only */
122 #define VSV_MODEM_CTL_UPDATE 2 /* from service processor only */
123 #define VSV_CLOSE_PROTOCOL   3
124
125 /* query verbs */
126 #define VSV_SEND_VERSION_NUMBER 1
127 #define VSV_SEND_MODEM_CTL_STATUS 2
128
129 /* yes, these masks are not consecutive. */
130 #define HVSI_TSDTR 0x01
131 #define HVSI_TSCD  0x20
132
133 struct hvsi_header {
134         uint8_t  type;
135         uint8_t  len;
136         uint16_t seqno;
137 } __attribute__((packed));
138
139 struct hvsi_data {
140         uint8_t  type;
141         uint8_t  len;
142         uint16_t seqno;
143         uint8_t  data[HVSI_MAX_OUTGOING_DATA];
144 } __attribute__((packed));
145
146 struct hvsi_control {
147         uint8_t  type;
148         uint8_t  len;
149         uint16_t seqno;
150         uint16_t verb;
151         /* optional depending on verb: */
152         uint32_t word;
153         uint32_t mask;
154 } __attribute__((packed));
155
156 struct hvsi_query {
157         uint8_t  type;
158         uint8_t  len;
159         uint16_t seqno;
160         uint16_t verb;
161 } __attribute__((packed));
162
163 struct hvsi_query_response {
164         uint8_t  type;
165         uint8_t  len;
166         uint16_t seqno;
167         uint16_t verb;
168         uint16_t query_seqno;
169         union {
170                 uint8_t  version;
171                 uint32_t mctrl_word;
172         } u;
173 } __attribute__((packed));
174
175 static inline int is_open(struct hvsi_struct *hp)
176 {
177         /* if we're waiting for an mctrl then we're already open */
178         return (hp->state == HVSI_OPEN)
179                         || (hp->state == HVSI_WAIT_FOR_MCTRL_RESPONSE);
180 }
181
182 static inline void print_state(struct hvsi_struct *hp)
183 {
184 #ifdef DEBUG
185         static const char *state_names[] = {
186                 "HVSI_CLOSED",
187                 "HVSI_WAIT_FOR_VER_RESPONSE",
188                 "HVSI_WAIT_FOR_VER_QUERY",
189                 "HVSI_OPEN",
190                 "HVSI_WAIT_FOR_MCTRL_RESPONSE",
191         };
192         const char *name = state_names[hp->state];
193
194         if (hp->state > (sizeof(state_names)/sizeof(char*)))
195                 name = "UNKNOWN";
196
197         pr_debug("hvsi%i: state = %s\n", hp->index, name);
198 #endif /* DEBUG */
199 }
200
201 static inline void __set_state(struct hvsi_struct *hp, int state)
202 {
203         hp->state = state;
204         print_state(hp);
205         wake_up_all(&hp->stateq);
206 }
207
208 static inline void set_state(struct hvsi_struct *hp, int state)
209 {
210         unsigned long flags;
211
212         spin_lock_irqsave(&hp->lock, flags);
213         __set_state(hp, state);
214         spin_unlock_irqrestore(&hp->lock, flags);
215 }
216
217 static inline int len_packet(const uint8_t *packet)
218 {
219         return (int)((struct hvsi_header *)packet)->len;
220 }
221
222 static inline int is_header(const uint8_t *packet)
223 {
224         struct hvsi_header *header = (struct hvsi_header *)packet;
225         return header->type >= VS_QUERY_RESPONSE_PACKET_HEADER;
226 }
227
228 static inline int got_packet(const struct hvsi_struct *hp, uint8_t *packet)
229 {
230         if (hp->inbuf_end < packet + sizeof(struct hvsi_header))
231                 return 0; /* don't even have the packet header */
232
233         if (hp->inbuf_end < (packet + len_packet(packet)))
234                 return 0; /* don't have the rest of the packet */
235
236         return 1;
237 }
238
239 /* shift remaining bytes in packetbuf down */
240 static void compact_inbuf(struct hvsi_struct *hp, uint8_t *read_to)
241 {
242         int remaining = (int)(hp->inbuf_end - read_to);
243
244         pr_debug("%s: %i chars remain\n", __FUNCTION__, remaining);
245
246         if (read_to != hp->inbuf)
247                 memmove(hp->inbuf, read_to, remaining);
248
249         hp->inbuf_end = hp->inbuf + remaining;
250 }
251
252 #ifdef DEBUG
253 #define dbg_dump_packet(packet) dump_packet(packet)
254 #define dbg_dump_hex(data, len) dump_hex(data, len)
255 #else
256 #define dbg_dump_packet(packet) do { } while (0)
257 #define dbg_dump_hex(data, len) do { } while (0)
258 #endif
259
260 static void dump_hex(const uint8_t *data, int len)
261 {
262         int i;
263
264         printk("    ");
265         for (i=0; i < len; i++)
266                 printk("%.2x", data[i]);
267
268         printk("\n    ");
269         for (i=0; i < len; i++) {
270                 if (isprint(data[i]))
271                         printk("%c", data[i]);
272                 else
273                         printk(".");
274         }
275         printk("\n");
276 }
277
278 static void dump_packet(uint8_t *packet)
279 {
280         struct hvsi_header *header = (struct hvsi_header *)packet;
281
282         printk("type 0x%x, len %i, seqno %i:\n", header->type, header->len,
283                         header->seqno);
284
285         dump_hex(packet, header->len);
286 }
287
288 /* can't use hvc_get_chars because that strips CRs */
289 static int hvsi_read(struct hvsi_struct *hp, char *buf, int count)
290 {
291         unsigned long got;
292
293         if (plpar_hcall(H_GET_TERM_CHAR, hp->vtermno, 0, 0, 0, &got,
294                         (unsigned long *)buf, (unsigned long *)buf+1) == H_Success)
295                 return got;
296         return 0;
297 }
298
299 /*
300  * we can't call tty_hangup() directly here because we need to call that
301  * outside of our lock
302  */
303 static struct tty_struct *hvsi_recv_control(struct hvsi_struct *hp,
304                 uint8_t *packet)
305 {
306         struct tty_struct *to_hangup = NULL;
307         struct hvsi_control *header = (struct hvsi_control *)packet;
308
309         switch (header->verb) {
310                 case VSV_MODEM_CTL_UPDATE:
311                         if ((header->word & HVSI_TSCD) == 0) {
312                                 /* CD went away; no more connection */
313                                 pr_debug("hvsi%i: CD dropped\n", hp->index);
314                                 hp->mctrl &= TIOCM_CD;
315                                 if (!(hp->tty->flags & CLOCAL))
316                                         to_hangup = hp->tty;
317                         }
318                         break;
319                 case VSV_CLOSE_PROTOCOL:
320                         printk(KERN_DEBUG
321                                 "hvsi%i: service processor closed connection!\n", hp->index);
322                         __set_state(hp, HVSI_CLOSED);
323                         to_hangup = hp->tty;
324                         hp->tty = NULL;
325                         break;
326                 default:
327                         printk(KERN_WARNING "hvsi%i: unknown HVSI control packet: ",
328                                 hp->index);
329                         dump_packet(packet);
330                         break;
331         }
332
333         return to_hangup;
334 }
335
336 static void hvsi_recv_response(struct hvsi_struct *hp, uint8_t *packet)
337 {
338         struct hvsi_query_response *resp = (struct hvsi_query_response *)packet;
339
340         switch (hp->state) {
341                 case HVSI_WAIT_FOR_VER_RESPONSE:
342                         __set_state(hp, HVSI_WAIT_FOR_VER_QUERY);
343                         break;
344                 case HVSI_WAIT_FOR_MCTRL_RESPONSE:
345                         hp->mctrl = 0;
346                         if (resp->u.mctrl_word & HVSI_TSDTR)
347                                 hp->mctrl |= TIOCM_DTR;
348                         if (resp->u.mctrl_word & HVSI_TSCD)
349                                 hp->mctrl |= TIOCM_CD;
350                         __set_state(hp, HVSI_OPEN);
351                         break;
352                 default:
353                         printk(KERN_ERR "hvsi%i: unexpected query response: ", hp->index);
354                         dump_packet(packet);
355                         break;
356         }
357 }
358
359 /* respond to service processor's version query */
360 static int hvsi_version_respond(struct hvsi_struct *hp, uint16_t query_seqno)
361 {
362         struct hvsi_query_response packet __ALIGNED__;
363         int wrote;
364
365         packet.type = VS_QUERY_RESPONSE_PACKET_HEADER;
366         packet.len = sizeof(struct hvsi_query_response);
367         packet.seqno = atomic_inc_return(&hp->seqno);
368         packet.verb = VSV_SEND_VERSION_NUMBER;
369         packet.u.version = HVSI_VERSION;
370         packet.query_seqno = query_seqno+1;
371
372         pr_debug("%s: sending %i bytes\n", __FUNCTION__, packet.len);
373         dbg_dump_hex((uint8_t*)&packet, packet.len);
374
375         wrote = hvc_put_chars(hp->vtermno, (char *)&packet, packet.len);
376         if (wrote != packet.len) {
377                 printk(KERN_ERR "hvsi%i: couldn't send query response!\n",
378                         hp->index);
379                 return -EIO;
380         }
381
382         return 0;
383 }
384
385 static void hvsi_recv_query(struct hvsi_struct *hp, uint8_t *packet)
386 {
387         struct hvsi_query *query = (struct hvsi_query *)packet;
388
389         switch (hp->state) {
390                 case HVSI_WAIT_FOR_VER_QUERY:
391                         __set_state(hp, HVSI_OPEN);
392                         hvsi_version_respond(hp, query->seqno);
393                         break;
394                 default:
395                         printk(KERN_ERR "hvsi%i: unexpected query: ", hp->index);
396                         dump_packet(packet);
397                         break;
398         }
399 }
400
401 static void hvsi_insert_chars(struct hvsi_struct *hp, const char *buf, int len)
402 {
403         int i;
404
405         for (i=0; i < len; i++) {
406                 char c = buf[i];
407 #ifdef CONFIG_MAGIC_SYSRQ
408                 if (c == '\0') {
409                         hp->sysrq = 1;
410                         continue;
411                 } else if (hp->sysrq) {
412                         handle_sysrq(c, NULL, hp->tty);
413                         hp->sysrq = 0;
414                         continue;
415                 }
416 #endif /* CONFIG_MAGIC_SYSRQ */
417                 tty_insert_flip_char(hp->tty, c, 0);
418         }
419 }
420
421 /*
422  * We could get 252 bytes of data at once here. But the tty layer only
423  * throttles us at TTY_THRESHOLD_THROTTLE (128) bytes, so we could overflow
424  * it. Accordingly we won't send more than 128 bytes at a time to the flip
425  * buffer, which will give the tty buffer a chance to throttle us. Should the
426  * value of TTY_THRESHOLD_THROTTLE change in n_tty.c, this code should be
427  * revisited.
428  */
429 #define TTY_THRESHOLD_THROTTLE 128
430 static struct tty_struct *hvsi_recv_data(struct hvsi_struct *hp,
431                 const uint8_t *packet)
432 {
433         const struct hvsi_header *header = (const struct hvsi_header *)packet;
434         const uint8_t *data = packet + sizeof(struct hvsi_header);
435         int datalen = header->len - sizeof(struct hvsi_header);
436         int overflow = datalen - TTY_THRESHOLD_THROTTLE;
437
438         pr_debug("queueing %i chars '%.*s'\n", datalen, datalen, data);
439
440         if (datalen == 0)
441                 return NULL;
442
443         if (overflow > 0) {
444                 pr_debug("%s: got >TTY_THRESHOLD_THROTTLE bytes\n", __FUNCTION__);
445                 datalen = TTY_THRESHOLD_THROTTLE;
446         }
447
448         hvsi_insert_chars(hp, data, datalen);
449
450         if (overflow > 0) {
451                 /*
452                  * we still have more data to deliver, so we need to save off the
453                  * overflow and send it later
454                  */
455                 pr_debug("%s: deferring overflow\n", __FUNCTION__);
456                 memcpy(hp->throttle_buf, data + TTY_THRESHOLD_THROTTLE, overflow);
457                 hp->n_throttle = overflow;
458         }
459
460         return hp->tty;
461 }
462
463 /*
464  * Returns true/false indicating data successfully read from hypervisor.
465  * Used both to get packets for tty connections and to advance the state
466  * machine during console handshaking (in which case tty = NULL and we ignore
467  * incoming data).
468  */
469 static int hvsi_load_chunk(struct hvsi_struct *hp, struct tty_struct **flip,
470                 struct tty_struct **hangup)
471 {
472         uint8_t *packet = hp->inbuf;
473         int chunklen;
474
475         *flip = NULL;
476         *hangup = NULL;
477
478         chunklen = hvsi_read(hp, hp->inbuf_end, HVSI_MAX_READ);
479         if (chunklen == 0)
480                 return 0;
481
482         pr_debug("%s: got %i bytes\n", __FUNCTION__, chunklen);
483         dbg_dump_hex(hp->inbuf_end, chunklen);
484
485         hp->inbuf_end += chunklen;
486
487         /* handle all completed packets */
488         while ((packet < hp->inbuf_end) && got_packet(hp, packet)) {
489                 struct hvsi_header *header = (struct hvsi_header *)packet;
490
491                 if (!is_header(packet)) {
492                         printk(KERN_ERR "hvsi%i: got malformed packet\n", hp->index);
493                         /* skip bytes until we find a header or run out of data */
494                         while ((packet < hp->inbuf_end) && (!is_header(packet)))
495                                 packet++;
496                         continue;
497                 }
498
499                 pr_debug("%s: handling %i-byte packet\n", __FUNCTION__,
500                                 len_packet(packet));
501                 dbg_dump_packet(packet);
502
503                 switch (header->type) {
504                         case VS_DATA_PACKET_HEADER:
505                                 if (!is_open(hp))
506                                         break;
507                                 if (hp->tty == NULL)
508                                         break; /* no tty buffer to put data in */
509                                 *flip = hvsi_recv_data(hp, packet);
510                                 break;
511                         case VS_CONTROL_PACKET_HEADER:
512                                 *hangup = hvsi_recv_control(hp, packet);
513                                 break;
514                         case VS_QUERY_RESPONSE_PACKET_HEADER:
515                                 hvsi_recv_response(hp, packet);
516                                 break;
517                         case VS_QUERY_PACKET_HEADER:
518                                 hvsi_recv_query(hp, packet);
519                                 break;
520                         default:
521                                 printk(KERN_ERR "hvsi%i: unknown HVSI packet type 0x%x\n",
522                                                 hp->index, header->type);
523                                 dump_packet(packet);
524                                 break;
525                 }
526
527                 packet += len_packet(packet);
528
529                 if (*hangup) {
530                         pr_debug("%s: hangup\n", __FUNCTION__);
531                         /*
532                          * we need to send the hangup now before receiving any more data.
533                          * If we get "data, hangup, data", we can't deliver the second
534                          * data before the hangup.
535                          */
536                         break;
537                 }
538         }
539
540         compact_inbuf(hp, packet);
541
542         return 1;
543 }
544
545 static void hvsi_send_overflow(struct hvsi_struct *hp)
546 {
547         pr_debug("%s: delivering %i bytes overflow\n", __FUNCTION__,
548                         hp->n_throttle);
549
550         hvsi_insert_chars(hp, hp->throttle_buf, hp->n_throttle);
551         hp->n_throttle = 0;
552 }
553
554 /*
555  * must get all pending data because we only get an irq on empty->non-empty
556  * transition
557  */
558 static irqreturn_t hvsi_interrupt(int irq, void *arg, struct pt_regs *regs)
559 {
560         struct hvsi_struct *hp = (struct hvsi_struct *)arg;
561         struct tty_struct *flip;
562         struct tty_struct *hangup;
563         unsigned long flags;
564         irqreturn_t handled = IRQ_NONE;
565         int again = 1;
566
567         pr_debug("%s\n", __FUNCTION__);
568
569         while (again) {
570                 spin_lock_irqsave(&hp->lock, flags);
571                 again = hvsi_load_chunk(hp, &flip, &hangup);
572                 handled = IRQ_HANDLED;
573                 spin_unlock_irqrestore(&hp->lock, flags);
574
575                 /*
576                  * we have to call tty_flip_buffer_push() and tty_hangup() outside our
577                  * spinlock. But we also have to keep going until we've read all the
578                  * available data.
579                  */
580
581                 if (flip) {
582                         /* there was data put in the tty flip buffer */
583                         tty_flip_buffer_push(flip);
584                         flip = NULL;
585                 }
586
587                 if (hangup) {
588                         tty_hangup(hangup);
589                 }
590         }
591
592         spin_lock_irqsave(&hp->lock, flags);
593         if (hp->tty && hp->n_throttle
594                         && (!test_bit(TTY_THROTTLED, &hp->tty->flags))) {
595                 /* we weren't hung up and we weren't throttled, so we can deliver the
596                  * rest now */
597                 flip = hp->tty;
598                 hvsi_send_overflow(hp);
599         }
600         spin_unlock_irqrestore(&hp->lock, flags);
601
602         if (flip) {
603                 tty_flip_buffer_push(flip);
604         }
605
606         return handled;
607 }
608
609 /* for boot console, before the irq handler is running */
610 static int __init poll_for_state(struct hvsi_struct *hp, int state)
611 {
612         unsigned long end_jiffies = jiffies + HVSI_TIMEOUT;
613
614         for (;;) {
615                 hvsi_interrupt(hp->virq, (void *)hp, NULL); /* get pending data */
616
617                 if (hp->state == state)
618                         return 0;
619
620                 mdelay(5);
621                 if (time_after(jiffies, end_jiffies))
622                         return -EIO;
623         }
624 }
625
626 /* wait for irq handler to change our state */
627 static int wait_for_state(struct hvsi_struct *hp, int state)
628 {
629         unsigned long end_jiffies = jiffies + HVSI_TIMEOUT;
630         unsigned long timeout;
631         int ret = 0;
632
633         DECLARE_WAITQUEUE(myself, current);
634         set_current_state(TASK_INTERRUPTIBLE);
635         add_wait_queue(&hp->stateq, &myself);
636
637         for (;;) {
638                 set_current_state(TASK_INTERRUPTIBLE);
639                 if (hp->state == state)
640                         break;
641                 timeout = end_jiffies - jiffies;
642                 if (time_after(jiffies, end_jiffies)) {
643                         ret = -EIO;
644                         break;
645                 }
646                 schedule_timeout(timeout);
647         }
648         remove_wait_queue(&hp->stateq, &myself);
649         set_current_state(TASK_RUNNING);
650
651         return ret;
652 }
653
654 static int hvsi_query(struct hvsi_struct *hp, uint16_t verb)
655 {
656         struct hvsi_query packet __ALIGNED__;
657         int wrote;
658
659         packet.type = VS_QUERY_PACKET_HEADER;
660         packet.len = sizeof(struct hvsi_query);
661         packet.seqno = atomic_inc_return(&hp->seqno);
662         packet.verb = verb;
663
664         pr_debug("%s: sending %i bytes\n", __FUNCTION__, packet.len);
665         dbg_dump_hex((uint8_t*)&packet, packet.len);
666
667         wrote = hvc_put_chars(hp->vtermno, (char *)&packet, packet.len);
668         if (wrote != packet.len) {
669                 printk(KERN_ERR "hvsi%i: couldn't send query (%i)!\n", hp->index,
670                         wrote);
671                 return -EIO;
672         }
673
674         return 0;
675 }
676
677 static int hvsi_get_mctrl(struct hvsi_struct *hp)
678 {
679         int ret;
680
681         set_state(hp, HVSI_WAIT_FOR_MCTRL_RESPONSE);
682         hvsi_query(hp, VSV_SEND_MODEM_CTL_STATUS);
683
684         ret = hvsi_wait(hp, HVSI_OPEN);
685         if (ret < 0) {
686                 printk(KERN_ERR "hvsi%i: didn't get modem flags\n", hp->index);
687                 set_state(hp, HVSI_OPEN);
688                 return ret;
689         }
690
691         pr_debug("%s: mctrl 0x%x\n", __FUNCTION__, hp->mctrl);
692
693         return 0;
694 }
695
696 /* note that we can only set DTR */
697 static int hvsi_set_mctrl(struct hvsi_struct *hp, uint16_t mctrl)
698 {
699         struct hvsi_control packet __ALIGNED__;
700         int wrote;
701
702         packet.type = VS_CONTROL_PACKET_HEADER,
703         packet.seqno = atomic_inc_return(&hp->seqno);
704         packet.len = sizeof(struct hvsi_control);
705         packet.verb = VSV_SET_MODEM_CTL;
706         packet.mask = HVSI_TSDTR;
707
708         if (mctrl & TIOCM_DTR)
709                 packet.word = HVSI_TSDTR;
710
711         pr_debug("%s: sending %i bytes\n", __FUNCTION__, packet.len);
712         dbg_dump_hex((uint8_t*)&packet, packet.len);
713
714         wrote = hvc_put_chars(hp->vtermno, (char *)&packet, packet.len);
715         if (wrote != packet.len) {
716                 printk(KERN_ERR "hvsi%i: couldn't set DTR!\n", hp->index);
717                 return -EIO;
718         }
719
720         return 0;
721 }
722
723 static void hvsi_drain_input(struct hvsi_struct *hp)
724 {
725         uint8_t buf[HVSI_MAX_READ] __ALIGNED__;
726         unsigned long end_jiffies = jiffies + HVSI_TIMEOUT;
727
728         while (time_before(end_jiffies, jiffies))
729                 if (0 == hvsi_read(hp, buf, HVSI_MAX_READ))
730                         break;
731 }
732
733 static int hvsi_handshake(struct hvsi_struct *hp)
734 {
735         int ret;
736
737         /*
738          * We could have a CLOSE or other data waiting for us before we even try
739          * to open; try to throw it all away so we don't get confused. (CLOSE
740          * is the first message sent up the pipe when the FSP comes online. We
741          * need to distinguish between "it came up a while ago and we're the first
742          * user" and "it was just reset before it saw our handshake packet".)
743          */
744         hvsi_drain_input(hp);
745
746         set_state(hp, HVSI_WAIT_FOR_VER_RESPONSE);
747         ret = hvsi_query(hp, VSV_SEND_VERSION_NUMBER);
748         if (ret < 0) {
749                 printk(KERN_ERR "hvsi%i: couldn't send version query\n", hp->index);
750                 return ret;
751         }
752
753         ret = hvsi_wait(hp, HVSI_OPEN);
754         if (ret < 0)
755                 return ret;
756
757         return 0;
758 }
759
760 static int hvsi_put_chars(struct hvsi_struct *hp, const char *buf, int count)
761 {
762         struct hvsi_data packet __ALIGNED__;
763         int ret;
764
765         BUG_ON(count > HVSI_MAX_OUTGOING_DATA);
766
767         packet.type = VS_DATA_PACKET_HEADER;
768         packet.seqno = atomic_inc_return(&hp->seqno);
769         packet.len = count + sizeof(struct hvsi_header);
770         memcpy(&packet.data, buf, count);
771
772         ret = hvc_put_chars(hp->vtermno, (char *)&packet, packet.len);
773         if (ret == packet.len) {
774                 /* return the number of chars written, not the packet length */
775                 return count;
776         }
777         return ret; /* return any errors */
778 }
779
780 static void hvsi_close_protocol(struct hvsi_struct *hp)
781 {
782         struct hvsi_control packet __ALIGNED__;
783
784         packet.type = VS_CONTROL_PACKET_HEADER;
785         packet.seqno = atomic_inc_return(&hp->seqno);
786         packet.len = 6;
787         packet.verb = VSV_CLOSE_PROTOCOL;
788
789         pr_debug("%s: sending %i bytes\n", __FUNCTION__, packet.len);
790         dbg_dump_hex((uint8_t*)&packet, packet.len);
791
792         hvc_put_chars(hp->vtermno, (char *)&packet, packet.len);
793 }
794
795 static int hvsi_open(struct tty_struct *tty, struct file *filp)
796 {
797         struct hvsi_struct *hp;
798         unsigned long flags;
799         int line = tty->index;
800         int ret;
801
802         pr_debug("%s\n", __FUNCTION__);
803
804         if (line < 0 || line >= hvsi_count)
805                 return -ENODEV;
806         hp = &hvsi_ports[line];
807
808         tty->driver_data = hp;
809         tty->low_latency = 1; /* avoid throttle/tty_flip_buffer_push race */
810
811         spin_lock_irqsave(&hp->lock, flags);
812         hp->tty = tty;
813         hp->count++;
814         atomic_set(&hp->seqno, 0);
815         h_vio_signal(hp->vtermno, VIO_IRQ_ENABLE);
816         spin_unlock_irqrestore(&hp->lock, flags);
817
818         if (hp->flags & HVSI_CONSOLE)
819                 return 0; /* this has already been handshaked as the console */
820
821         ret = hvsi_handshake(hp);
822         if (ret < 0) {
823                 printk(KERN_ERR "%s: HVSI handshaking failed\n", tty->name);
824                 return ret;
825         }
826
827         ret = hvsi_get_mctrl(hp);
828         if (ret < 0) {
829                 printk(KERN_ERR "%s: couldn't get initial modem flags\n", tty->name);
830                 return ret;
831         }
832
833         ret = hvsi_set_mctrl(hp, hp->mctrl | TIOCM_DTR);
834         if (ret < 0) {
835                 printk(KERN_ERR "%s: couldn't set DTR\n", tty->name);
836                 return ret;
837         }
838
839         return 0;
840 }
841
842 /* wait for hvsi_write_worker to empty hp->outbuf */
843 static void hvsi_flush_output(struct hvsi_struct *hp)
844 {
845         unsigned long end_jiffies = jiffies + HVSI_TIMEOUT;
846         unsigned long timeout;
847
848         DECLARE_WAITQUEUE(myself, current);
849         set_current_state(TASK_UNINTERRUPTIBLE);
850         add_wait_queue(&hp->emptyq, &myself);
851
852         for (;;) {
853                 set_current_state(TASK_UNINTERRUPTIBLE);
854                 if (hp->n_outbuf <= 0)
855                         break;
856                 timeout = end_jiffies - jiffies;
857                 if (time_after(jiffies, end_jiffies))
858                         break;
859                 schedule_timeout(timeout);
860         }
861         remove_wait_queue(&hp->emptyq, &myself);
862         set_current_state(TASK_RUNNING);
863
864         /* 'writer' could still be pending if it didn't see n_outbuf = 0 yet */
865         cancel_delayed_work(&hp->writer);
866         flush_scheduled_work();
867
868         /*
869          * it's also possible that our timeout expired and hvsi_write_worker
870          * didn't manage to push outbuf. poof.
871          */
872         hp->n_outbuf = 0;
873 }
874
875 static void hvsi_close(struct tty_struct *tty, struct file *filp)
876 {
877         struct hvsi_struct *hp = tty->driver_data;
878         unsigned long flags;
879
880         pr_debug("%s\n", __FUNCTION__);
881
882         if (tty_hung_up_p(filp))
883                 return;
884
885         spin_lock_irqsave(&hp->lock, flags);
886
887         if (--hp->count == 0) {
888                 hp->tty = NULL;
889                 hp->inbuf_end = hp->inbuf; /* discard remaining partial packets */
890
891                 /* only close down connection if it is not the console */
892                 if (!(hp->flags & HVSI_CONSOLE)) {
893                         h_vio_signal(hp->vtermno, VIO_IRQ_DISABLE); /* no more irqs */
894                         __set_state(hp, HVSI_CLOSED);
895                         /*
896                          * any data delivered to the tty layer after this will be
897                          * discarded (except for XON/XOFF)
898                          */
899                         tty->closing = 1;
900
901                         spin_unlock_irqrestore(&hp->lock, flags);
902
903                         /* let any existing irq handlers finish. no more will start. */
904                         synchronize_irq(hp->virq);
905
906                         /* hvsi_write_worker will re-schedule until outbuf is empty. */
907                         hvsi_flush_output(hp);
908
909                         /* tell FSP to stop sending data */
910                         hvsi_close_protocol(hp);
911
912                         /*
913                          * drain anything FSP is still in the middle of sending, and let
914                          * hvsi_handshake drain the rest on the next open.
915                          */
916                         hvsi_drain_input(hp);
917
918                         spin_lock_irqsave(&hp->lock, flags);
919                 }
920         } else if (hp->count < 0)
921                 printk(KERN_ERR "hvsi_close %lu: oops, count is %d\n",
922                        hp - hvsi_ports, hp->count);
923
924         spin_unlock_irqrestore(&hp->lock, flags);
925 }
926
927 static void hvsi_hangup(struct tty_struct *tty)
928 {
929         struct hvsi_struct *hp = tty->driver_data;
930
931         pr_debug("%s\n", __FUNCTION__);
932
933         hp->count = 0;
934         hp->tty = NULL;
935 }
936
937 /* called with hp->lock held */
938 static void hvsi_push(struct hvsi_struct *hp)
939 {
940         int n;
941
942         if (hp->n_outbuf <= 0)
943                 return;
944
945         n = hvsi_put_chars(hp, hp->outbuf, hp->n_outbuf);
946         if (n != 0) {
947                 /*
948                  * either all data was sent or there was an error, and we throw away
949                  * data on error.
950                  */
951                 hp->n_outbuf = 0;
952         }
953 }
954
955 /* hvsi_write_worker will keep rescheduling itself until outbuf is empty */
956 static void hvsi_write_worker(void *arg)
957 {
958         struct hvsi_struct *hp = (struct hvsi_struct *)arg;
959         unsigned long flags;
960 #ifdef DEBUG
961         static long start_j = 0;
962
963         if (start_j == 0)
964                 start_j = jiffies;
965 #endif /* DEBUG */
966
967         spin_lock_irqsave(&hp->lock, flags);
968
969         hvsi_push(hp);
970         if (hp->n_outbuf > 0)
971                 schedule_delayed_work(&hp->writer, 10);
972         else {
973 #ifdef DEBUG
974                 pr_debug("%s: outbuf emptied after %li jiffies\n", __FUNCTION__,
975                                 jiffies - start_j);
976                 start_j = 0;
977 #endif /* DEBUG */
978                 wake_up_all(&hp->emptyq);
979                 if (test_bit(TTY_DO_WRITE_WAKEUP, &hp->tty->flags)
980                                 && hp->tty->ldisc.write_wakeup)
981                         hp->tty->ldisc.write_wakeup(hp->tty);
982                 wake_up_interruptible(&hp->tty->write_wait);
983         }
984
985         spin_unlock_irqrestore(&hp->lock, flags);
986 }
987
988 static int hvsi_write_room(struct tty_struct *tty)
989 {
990         struct hvsi_struct *hp = (struct hvsi_struct *)tty->driver_data;
991
992         return N_OUTBUF - hp->n_outbuf;
993 }
994
995 static int hvsi_chars_in_buffer(struct tty_struct *tty)
996 {
997         struct hvsi_struct *hp = (struct hvsi_struct *)tty->driver_data;
998
999         return hp->n_outbuf;
1000 }
1001
1002 static int hvsi_write(struct tty_struct *tty, int from_user,
1003                      const unsigned char *buf, int count)
1004 {
1005         struct hvsi_struct *hp = tty->driver_data;
1006         const char *source = buf;
1007         char *kbuf = NULL;
1008         unsigned long flags;
1009         int total = 0;
1010         int origcount = count;
1011
1012         if (from_user) {
1013                 kbuf = kmalloc(count, GFP_KERNEL);
1014                 if (kbuf == NULL)
1015                         return -ENOMEM;
1016                 if (copy_from_user(kbuf, buf, count)) {
1017                         kfree(kbuf);
1018                         return -EFAULT;
1019                 }
1020                 source = kbuf;
1021         }
1022
1023         spin_lock_irqsave(&hp->lock, flags);
1024
1025         if (!is_open(hp)) {
1026                 /* we're either closing or not yet open; don't accept data */
1027                 pr_debug("%s: not open\n", __FUNCTION__);
1028                 goto out;
1029         }
1030
1031         /*
1032          * when the hypervisor buffer (16K) fills, data will stay in hp->outbuf
1033          * and hvsi_write_worker will be scheduled. subsequent hvsi_write() calls
1034          * will see there is no room in outbuf and return.
1035          */
1036         while ((count > 0) && (hvsi_write_room(hp->tty) > 0)) {
1037                 int chunksize = min(count, hvsi_write_room(hp->tty));
1038
1039                 BUG_ON(hp->n_outbuf < 0);
1040                 memcpy(hp->outbuf + hp->n_outbuf, source, chunksize);
1041                 hp->n_outbuf += chunksize;
1042
1043                 total += chunksize;
1044                 source += chunksize;
1045                 count -= chunksize;
1046                 hvsi_push(hp);
1047         }
1048
1049         if (hp->n_outbuf > 0) {
1050                 /*
1051                  * we weren't able to write it all to the hypervisor.
1052                  * schedule another push attempt.
1053                  */
1054                 schedule_delayed_work(&hp->writer, 10);
1055         }
1056
1057 out:
1058         spin_unlock_irqrestore(&hp->lock, flags);
1059
1060         if (from_user)
1061                 kfree(kbuf);
1062
1063         if (total != origcount)
1064                 pr_debug("%s: wanted %i, only wrote %i\n", __FUNCTION__, origcount,
1065                         total);
1066
1067         return total;
1068 }
1069
1070 /*
1071  * I have never seen throttle or unthrottle called, so this little throttle
1072  * buffering scheme may or may not work.
1073  */
1074 static void hvsi_throttle(struct tty_struct *tty)
1075 {
1076         struct hvsi_struct *hp = (struct hvsi_struct *)tty->driver_data;
1077
1078         pr_debug("%s\n", __FUNCTION__);
1079
1080         h_vio_signal(hp->vtermno, VIO_IRQ_DISABLE);
1081 }
1082
1083 static void hvsi_unthrottle(struct tty_struct *tty)
1084 {
1085         struct hvsi_struct *hp = (struct hvsi_struct *)tty->driver_data;
1086         unsigned long flags;
1087         int shouldflip = 0;
1088
1089         pr_debug("%s\n", __FUNCTION__);
1090
1091         spin_lock_irqsave(&hp->lock, flags);
1092         if (hp->n_throttle) {
1093                 hvsi_send_overflow(hp);
1094                 shouldflip = 1;
1095         }
1096         spin_unlock_irqrestore(&hp->lock, flags);
1097
1098         if (shouldflip)
1099                 tty_flip_buffer_push(hp->tty);
1100
1101         h_vio_signal(hp->vtermno, VIO_IRQ_ENABLE);
1102 }
1103
1104 static int hvsi_tiocmget(struct tty_struct *tty, struct file *file)
1105 {
1106         struct hvsi_struct *hp = (struct hvsi_struct *)tty->driver_data;
1107
1108         hvsi_get_mctrl(hp);
1109         return hp->mctrl;
1110 }
1111
1112 static int hvsi_tiocmset(struct tty_struct *tty, struct file *file,
1113                 unsigned int set, unsigned int clear)
1114 {
1115         struct hvsi_struct *hp = (struct hvsi_struct *)tty->driver_data;
1116         unsigned long flags;
1117         uint16_t new_mctrl;
1118
1119         /* we can only alter DTR */
1120         clear &= TIOCM_DTR;
1121         set &= TIOCM_DTR;
1122
1123         spin_lock_irqsave(&hp->lock, flags);
1124
1125         new_mctrl = (hp->mctrl & ~clear) | set;
1126
1127         if (hp->mctrl != new_mctrl) {
1128                 hvsi_set_mctrl(hp, new_mctrl);
1129                 hp->mctrl = new_mctrl;
1130         }
1131         spin_unlock_irqrestore(&hp->lock, flags);
1132
1133         return 0;
1134 }
1135
1136
1137 static struct tty_operations hvsi_ops = {
1138         .open = hvsi_open,
1139         .close = hvsi_close,
1140         .write = hvsi_write,
1141         .hangup = hvsi_hangup,
1142         .write_room = hvsi_write_room,
1143         .chars_in_buffer = hvsi_chars_in_buffer,
1144         .throttle = hvsi_throttle,
1145         .unthrottle = hvsi_unthrottle,
1146         .tiocmget = hvsi_tiocmget,
1147         .tiocmset = hvsi_tiocmset,
1148 };
1149
1150 static int __init hvsi_init(void)
1151 {
1152         int i;
1153
1154         hvsi_driver = alloc_tty_driver(hvsi_count);
1155         if (!hvsi_driver)
1156                 return -ENOMEM;
1157
1158         hvsi_driver->owner = THIS_MODULE;
1159         hvsi_driver->devfs_name = "hvsi/";
1160         hvsi_driver->driver_name = "hvsi";
1161         hvsi_driver->name = "hvsi";
1162         hvsi_driver->major = HVSI_MAJOR;
1163         hvsi_driver->minor_start = HVSI_MINOR;
1164         hvsi_driver->type = TTY_DRIVER_TYPE_SYSTEM;
1165         hvsi_driver->init_termios = tty_std_termios;
1166         hvsi_driver->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL;
1167         hvsi_driver->flags = TTY_DRIVER_REAL_RAW;
1168         tty_set_operations(hvsi_driver, &hvsi_ops);
1169
1170         for (i=0; i < hvsi_count; i++) {
1171                 struct hvsi_struct *hp = &hvsi_ports[i];
1172                 int ret = 1;
1173
1174                 ret = request_irq(hp->virq, hvsi_interrupt, SA_INTERRUPT, "hvsi", hp);
1175                 if (ret)
1176                         printk(KERN_ERR "HVSI: couldn't reserve irq 0x%x (error %i)\n",
1177                                 hp->virq, ret);
1178         }
1179         hvsi_wait = wait_for_state; /* irqs active now */
1180
1181         if (tty_register_driver(hvsi_driver))
1182                 panic("Couldn't register hvsi console driver\n");
1183
1184         printk(KERN_INFO "HVSI: registered %i devices\n", hvsi_count);
1185
1186         return 0;
1187 }
1188 device_initcall(hvsi_init);
1189
1190 /***** console (not tty) code: *****/
1191
1192 static void hvsi_console_print(struct console *console, const char *buf,
1193                 unsigned int count)
1194 {
1195         struct hvsi_struct *hp = &hvsi_ports[console->index];
1196         char c[HVSI_MAX_OUTGOING_DATA] __ALIGNED__;
1197         unsigned int i = 0, n = 0;
1198         int ret, donecr = 0;
1199
1200         mb();
1201         if (!is_open(hp))
1202                 return;
1203
1204         /*
1205          * ugh, we have to translate LF -> CRLF ourselves, in place.
1206          * copied from hvc_console.c:
1207          */
1208         while (count > 0 || i > 0) {
1209                 if (count > 0 && i < sizeof(c)) {
1210                         if (buf[n] == '\n' && !donecr) {
1211                                 c[i++] = '\r';
1212                                 donecr = 1;
1213                         } else {
1214                                 c[i++] = buf[n++];
1215                                 donecr = 0;
1216                                 --count;
1217                         }
1218                 } else {
1219                         ret = hvsi_put_chars(hp, c, i);
1220                         if (ret < 0)
1221                                 i = 0;
1222                         i -= ret;
1223                 }
1224         }
1225 }
1226
1227 static struct tty_driver *hvsi_console_device(struct console *console,
1228         int *index)
1229 {
1230         *index = console->index;
1231         return hvsi_driver;
1232 }
1233
1234 static int __init hvsi_console_setup(struct console *console, char *options)
1235 {
1236         struct hvsi_struct *hp = &hvsi_ports[console->index];
1237         int ret;
1238
1239         if (console->index < 0 || console->index >= hvsi_count)
1240                 return -1;
1241
1242         /* give the FSP a chance to change the baud rate when we re-open */
1243         hvsi_close_protocol(hp);
1244
1245         ret = hvsi_handshake(hp);
1246         if (ret < 0)
1247                 return ret;
1248
1249         ret = hvsi_get_mctrl(hp);
1250         if (ret < 0)
1251                 return ret;
1252
1253         ret = hvsi_set_mctrl(hp, hp->mctrl | TIOCM_DTR);
1254         if (ret < 0)
1255                 return ret;
1256
1257         hp->flags |= HVSI_CONSOLE;
1258
1259         return 0;
1260 }
1261
1262 static struct console hvsi_con_driver = {
1263         .name           = "hvsi",
1264         .write          = hvsi_console_print,
1265         .device         = hvsi_console_device,
1266         .setup          = hvsi_console_setup,
1267         .flags          = CON_PRINTBUFFER,
1268         .index          = -1,
1269 };
1270
1271 static int __init hvsi_console_init(void)
1272 {
1273         struct device_node *vty;
1274
1275         hvsi_wait = poll_for_state; /* no irqs yet; must poll */
1276
1277         /* search device tree for vty nodes */
1278         for (vty = of_find_compatible_node(NULL, "serial", "hvterm-protocol");
1279                         vty != NULL;
1280                         vty = of_find_compatible_node(vty, "serial", "hvterm-protocol")) {
1281                 struct hvsi_struct *hp;
1282                 uint32_t *vtermno;
1283                 uint32_t *irq;
1284
1285                 vtermno = (uint32_t *)get_property(vty, "reg", NULL);
1286                 irq = (uint32_t *)get_property(vty, "interrupts", NULL);
1287                 if (!vtermno || !irq)
1288                         continue;
1289
1290                 if (hvsi_count >= MAX_NR_HVSI_CONSOLES) {
1291                         of_node_put(vty);
1292                         break;
1293                 }
1294
1295                 hp = &hvsi_ports[hvsi_count];
1296                 INIT_WORK(&hp->writer, hvsi_write_worker, hp);
1297                 init_waitqueue_head(&hp->emptyq);
1298                 init_waitqueue_head(&hp->stateq);
1299                 hp->lock = SPIN_LOCK_UNLOCKED;
1300                 hp->index = hvsi_count;
1301                 hp->inbuf_end = hp->inbuf;
1302                 hp->state = HVSI_CLOSED;
1303                 hp->vtermno = *vtermno;
1304                 hp->virq = virt_irq_create_mapping(irq[0]);
1305                 if (hp->virq == NO_IRQ) {
1306                         printk(KERN_ERR "%s: couldn't create irq mapping for 0x%x\n",
1307                                 __FUNCTION__, hp->virq);
1308                         continue;
1309                 } else
1310                         hp->virq = irq_offset_up(hp->virq);
1311
1312                 hvsi_count++;
1313         }
1314
1315         if (hvsi_count)
1316                 register_console(&hvsi_con_driver);
1317         return 0;
1318 }
1319 console_initcall(hvsi_console_init);