vserver 1.9.3
[linux-2.6.git] / drivers / char / viocons.c
1 /* -*- linux-c -*-
2  *
3  *  drivers/char/viocons.c
4  *
5  *  iSeries Virtual Terminal
6  *
7  *  Authors: Dave Boutcher <boutcher@us.ibm.com>
8  *           Ryan Arnold <ryanarn@us.ibm.com>
9  *           Colin Devilbiss <devilbis@us.ibm.com>
10  *           Stephen Rothwell <sfr@au1.ibm.com>
11  *
12  * (C) Copyright 2000, 2001, 2002, 2003, 2004 IBM Corporation
13  *
14  * This program is free software;  you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License as
16  * published by the Free Software Foundation; either version 2 of the
17  * License, or (at your option) anyu later version.
18  *
19  * This program is distributed in the hope that it will be useful, but
20  * WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software Foundation,
26  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27  */
28 #include <linux/config.h>
29 #include <linux/version.h>
30 #include <linux/kernel.h>
31 #include <linux/proc_fs.h>
32 #include <linux/errno.h>
33 #include <linux/vmalloc.h>
34 #include <linux/mm.h>
35 #include <linux/console.h>
36 #include <linux/module.h>
37 #include <asm/uaccess.h>
38 #include <linux/init.h>
39 #include <linux/wait.h>
40 #include <linux/spinlock.h>
41 #include <asm/ioctls.h>
42 #include <linux/kd.h>
43 #include <linux/tty.h>
44 #include <linux/tty_flip.h>
45 #include <linux/sysrq.h>
46
47 #include <asm/iSeries/vio.h>
48
49 #include <asm/iSeries/HvLpEvent.h>
50 #include <asm/iSeries/HvCallEvent.h>
51 #include <asm/iSeries/HvLpConfig.h>
52 #include <asm/iSeries/HvCall.h>
53
54 #ifdef CONFIG_VT
55 #error You must turn off CONFIG_VT to use CONFIG_VIOCONS
56 #endif
57
58 #define VIOTTY_MAGIC (0x0DCB)
59 #define VTTY_PORTS 10
60
61 #define VIOCONS_KERN_WARN       KERN_WARNING "viocons: "
62 #define VIOCONS_KERN_INFO       KERN_INFO "viocons: "
63
64 static spinlock_t consolelock = SPIN_LOCK_UNLOCKED;
65 static spinlock_t consoleloglock = SPIN_LOCK_UNLOCKED;
66
67 #ifdef CONFIG_MAGIC_SYSRQ
68 static int vio_sysrq_pressed;
69 extern int sysrq_enabled;
70 #endif
71
72 /*
73  * The structure of the events that flow between us and OS/400.  You can't
74  * mess with this unless the OS/400 side changes too
75  */
76 struct viocharlpevent {
77         struct HvLpEvent event;
78         u32 reserved;
79         u16 version;
80         u16 subtype_result_code;
81         u8 virtual_device;
82         u8 len;
83         u8 data[VIOCHAR_MAX_DATA];
84 };
85
86 /*
87  * This is a place where we handle the distribution of memory
88  * for copy_from_user() calls.  The buffer_available array is to
89  * help us determine which buffer to use.
90  */
91 #define VIOCHAR_NUM_CFU_BUFFERS 7
92 static struct viocharlpevent viocons_cfu_buffer[VIOCHAR_NUM_CFU_BUFFERS];
93 static atomic_t viocons_cfu_buffer_available[VIOCHAR_NUM_CFU_BUFFERS];
94
95 #define VIOCHAR_WINDOW          10
96 #define VIOCHAR_HIGHWATERMARK   3
97
98 enum viocharsubtype {
99         viocharopen = 0x0001,
100         viocharclose = 0x0002,
101         viochardata = 0x0003,
102         viocharack = 0x0004,
103         viocharconfig = 0x0005
104 };
105
106 enum viochar_rc {
107         viochar_rc_ebusy = 1
108 };
109
110 #define VIOCHAR_NUM_BUF         16
111
112 /*
113  * Our port information.  We store a pointer to one entry in the
114  * tty_driver_data
115  */
116 static struct port_info {
117         int magic;
118         struct tty_struct *tty;
119         HvLpIndex lp;
120         u8 vcons;
121         u64 seq;        /* sequence number of last HV send */
122         u64 ack;        /* last ack from HV */
123 /*
124  * When we get writes faster than we can send it to the partition,
125  * buffer the data here. Note that used is a bit map of used buffers.
126  * It had better have enough bits to hold VIOCHAR_NUM_BUF the bitops assume
127  * it is a multiple of unsigned long
128  */
129         unsigned long used;
130         u8 *buffer[VIOCHAR_NUM_BUF];
131         int bufferBytes[VIOCHAR_NUM_BUF];
132         int curbuf;
133         int bufferOverflow;
134         int overflowMessage;
135 } port_info[VTTY_PORTS];
136
137 #define viochar_is_console(pi)  ((pi) == &port_info[0])
138 #define viochar_port(pi)        ((pi) - &port_info[0])
139
140 static void initDataEvent(struct viocharlpevent *viochar, HvLpIndex lp);
141
142 static struct tty_driver *viotty_driver;
143
144 void hvlog(char *fmt, ...)
145 {
146         int i;
147         unsigned long flags;
148         va_list args;
149         static char buf[256];
150
151         spin_lock_irqsave(&consoleloglock, flags);
152         va_start(args, fmt);
153         i = vscnprintf(buf, sizeof(buf) - 1, fmt, args);
154         va_end(args);
155         buf[i++] = '\r';
156         HvCall_writeLogBuffer(buf, i);
157         spin_unlock_irqrestore(&consoleloglock, flags);
158 }
159
160 void hvlogOutput(const char *buf, int count)
161 {
162         unsigned long flags;
163         int begin;
164         int index;
165         static const char cr = '\r';
166
167         begin = 0;
168         spin_lock_irqsave(&consoleloglock, flags);
169         for (index = 0; index < count; index++) {
170                 if (buf[index] == '\n') {
171                         /*
172                          * Start right after the last '\n' or at the zeroth
173                          * array position and output the number of characters
174                          * including the newline.
175                          */
176                         HvCall_writeLogBuffer(&buf[begin], index - begin + 1);
177                         begin = index + 1;
178                         HvCall_writeLogBuffer(&cr, 1);
179                 }
180         }
181         if ((index - begin) > 0)
182                 HvCall_writeLogBuffer(&buf[begin], index - begin);
183         spin_unlock_irqrestore(&consoleloglock, flags);
184 }
185
186 /*
187  * Make sure we're pointing to a valid port_info structure.  Shamelessly
188  * plagerized from serial.c
189  */
190 static inline int viotty_paranoia_check(struct port_info *pi,
191                                         char *name, const char *routine)
192 {
193         static const char *bad_pi_addr = VIOCONS_KERN_WARN
194                 "warning: bad address for port_info struct (%s) in %s\n";
195         static const char *badmagic = VIOCONS_KERN_WARN
196                 "warning: bad magic number for port_info struct (%s) in %s\n";
197
198         if ((pi < &port_info[0]) || (viochar_port(pi) > VTTY_PORTS)) {
199                 printk(bad_pi_addr, name, routine);
200                 return 1;
201         }
202         if (pi->magic != VIOTTY_MAGIC) {
203                 printk(badmagic, name, routine);
204                 return 1;
205         }
206         return 0;
207 }
208
209 /*
210  * This function should ONLY be called once from viocons_init2
211  */
212 static void viocons_init_cfu_buffer(void)
213 {
214         int i;
215
216         for (i = 1; i < VIOCHAR_NUM_CFU_BUFFERS; i++)
217                 atomic_set(&viocons_cfu_buffer_available[i], 1);
218 }
219
220 static struct viocharlpevent *viocons_get_cfu_buffer(void)
221 {
222         int i;
223
224         /*
225          * Grab the first available buffer.  It doesn't matter if we
226          * are interrupted during this array traversal as long as we
227          * get an available space.
228          */
229         for (i = 0; i < VIOCHAR_NUM_CFU_BUFFERS; i++)
230                 if (atomic_dec_if_positive(&viocons_cfu_buffer_available[i])
231                                 == 0 )
232                         return &viocons_cfu_buffer[i];
233         hvlog("\n\rviocons: viocons_get_cfu_buffer : no free buffers found");
234         return NULL;
235 }
236
237 static void viocons_free_cfu_buffer(struct viocharlpevent *buffer)
238 {
239         int i;
240
241         i = buffer - &viocons_cfu_buffer[0];
242         if (i >= (sizeof(viocons_cfu_buffer) / sizeof(viocons_cfu_buffer[0]))) {
243                 hvlog("\n\rviocons: viocons_free_cfu_buffer : buffer pointer not found in list.");
244                 return;
245         }
246         if (atomic_read(&viocons_cfu_buffer_available[i]) != 0) {
247                 hvlog("\n\rviocons: WARNING : returning unallocated cfu buffer.");
248                 return;
249         }
250         atomic_set(&viocons_cfu_buffer_available[i], 1);
251 }
252
253 /*
254  * Add data to our pending-send buffers.  
255  *
256  * NOTE: Don't use printk in here because it gets nastily recursive.
257  * hvlog can be used to log to the hypervisor buffer
258  */
259 static int buffer_add(struct port_info *pi, const char *buf, size_t len)
260 {
261         size_t bleft;
262         size_t curlen;
263         const char *curbuf;
264         int nextbuf;
265
266         curbuf = buf;
267         bleft = len;
268         while (bleft > 0) {
269                 /*
270                  * If there is no space left in the current buffer, we have
271                  * filled everything up, so return.  If we filled the previous
272                  * buffer we would already have moved to the next one.
273                  */
274                 if (pi->bufferBytes[pi->curbuf] == VIOCHAR_MAX_DATA) {
275                         hvlog ("\n\rviocons: No overflow buffer available for memcpy().\n");
276                         pi->bufferOverflow++;
277                         pi->overflowMessage = 1;
278                         break;
279                 }
280
281                 /*
282                  * Turn on the "used" bit for this buffer.  If it's already on,
283                  * that's fine.
284                  */
285                 set_bit(pi->curbuf, &pi->used);
286
287                 /*
288                  * See if this buffer has been allocated.  If not, allocate it.
289                  */
290                 if (pi->buffer[pi->curbuf] == NULL) {
291                         pi->buffer[pi->curbuf] =
292                             kmalloc(VIOCHAR_MAX_DATA, GFP_ATOMIC);
293                         if (pi->buffer[pi->curbuf] == NULL) {
294                                 hvlog("\n\rviocons: kmalloc failed allocating spaces for buffer %d.",
295                                         pi->curbuf);
296                                 break;
297                         }
298                 }
299
300                 /* Figure out how much we can copy into this buffer. */
301                 if (bleft < (VIOCHAR_MAX_DATA - pi->bufferBytes[pi->curbuf]))
302                         curlen = bleft;
303                 else
304                         curlen = VIOCHAR_MAX_DATA - pi->bufferBytes[pi->curbuf];
305
306                 /* Copy the data into the buffer. */
307                 memcpy(pi->buffer[pi->curbuf] + pi->bufferBytes[pi->curbuf],
308                                 curbuf, curlen);
309
310                 pi->bufferBytes[pi->curbuf] += curlen;
311                 curbuf += curlen;
312                 bleft -= curlen;
313
314                 /*
315                  * Now see if we've filled this buffer.  If not then
316                  * we'll try to use it again later.  If we've filled it
317                  * up then we'll advance the curbuf to the next in the
318                  * circular queue.
319                  */
320                 if (pi->bufferBytes[pi->curbuf] == VIOCHAR_MAX_DATA) {
321                         nextbuf = (pi->curbuf + 1) % VIOCHAR_NUM_BUF;
322                         /*
323                          * Move to the next buffer if it hasn't been used yet
324                          */
325                         if (test_bit(nextbuf, &pi->used) == 0)
326                                 pi->curbuf = nextbuf;
327                 }
328         }
329         return len - bleft;
330 }
331
332 /*
333  * Send pending data
334  *
335  * NOTE: Don't use printk in here because it gets nastily recursive.
336  * hvlog can be used to log to the hypervisor buffer
337  */
338 static void send_buffers(struct port_info *pi)
339 {
340         HvLpEvent_Rc hvrc;
341         int nextbuf;
342         struct viocharlpevent *viochar;
343         unsigned long flags;
344
345         spin_lock_irqsave(&consolelock, flags);
346
347         viochar = (struct viocharlpevent *)
348             vio_get_event_buffer(viomajorsubtype_chario);
349
350         /* Make sure we got a buffer */
351         if (viochar == NULL) {
352                 hvlog("\n\rviocons: Can't get viochar buffer in sendBuffers().");
353                 spin_unlock_irqrestore(&consolelock, flags);
354                 return;
355         }
356
357         if (pi->used == 0) {
358                 hvlog("\n\rviocons: in sendbuffers(), but no buffers used.\n");
359                 vio_free_event_buffer(viomajorsubtype_chario, viochar);
360                 spin_unlock_irqrestore(&consolelock, flags);
361                 return;
362         }
363
364         /*
365          * curbuf points to the buffer we're filling.  We want to
366          * start sending AFTER this one.  
367          */
368         nextbuf = (pi->curbuf + 1) % VIOCHAR_NUM_BUF;
369
370         /*
371          * Loop until we find a buffer with the used bit on
372          */
373         while (test_bit(nextbuf, &pi->used) == 0)
374                 nextbuf = (nextbuf + 1) % VIOCHAR_NUM_BUF;
375
376         initDataEvent(viochar, pi->lp);
377
378         /*
379          * While we have buffers with data, and our send window
380          * is open, send them
381          */
382         while ((test_bit(nextbuf, &pi->used)) &&
383                ((pi->seq - pi->ack) < VIOCHAR_WINDOW)) {
384                 viochar->len = pi->bufferBytes[nextbuf];
385                 viochar->event.xCorrelationToken = pi->seq++;
386                 viochar->event.xSizeMinus1 =
387                         offsetof(struct viocharlpevent, data) + viochar->len;
388
389                 memcpy(viochar->data, pi->buffer[nextbuf], viochar->len);
390
391                 hvrc = HvCallEvent_signalLpEvent(&viochar->event);
392                 if (hvrc) {
393                         /*
394                          * MUST unlock the spinlock before doing a printk
395                          */
396                         vio_free_event_buffer(viomajorsubtype_chario, viochar);
397                         spin_unlock_irqrestore(&consolelock, flags);
398
399                         printk(VIOCONS_KERN_WARN
400                                "error sending event! return code %d\n",
401                                (int)hvrc);
402                         return;
403                 }
404
405                 /*
406                  * clear the used bit, zero the number of bytes in
407                  * this buffer, and move to the next buffer
408                  */
409                 clear_bit(nextbuf, &pi->used);
410                 pi->bufferBytes[nextbuf] = 0;
411                 nextbuf = (nextbuf + 1) % VIOCHAR_NUM_BUF;
412         }
413
414         /*
415          * If we have emptied all the buffers, start at 0 again.
416          * this will re-use any allocated buffers
417          */
418         if (pi->used == 0) {
419                 pi->curbuf = 0;
420
421                 if (pi->overflowMessage)
422                         pi->overflowMessage = 0;
423
424                 if (pi->tty) {
425                         tty_wakeup(pi->tty);
426                 }
427         }
428
429         vio_free_event_buffer(viomajorsubtype_chario, viochar);
430         spin_unlock_irqrestore(&consolelock, flags);
431 }
432
433 /*
434  * Our internal writer.  Gets called both from the console device and
435  * the tty device.  the tty pointer will be NULL if called from the console.
436  * Return total number of bytes "written".
437  *
438  * NOTE: Don't use printk in here because it gets nastily recursive.  hvlog
439  * can be used to log to the hypervisor buffer
440  */
441 static int internal_write(struct port_info *pi, const char *buf,
442                           size_t len, struct viocharlpevent *viochar)
443 {
444         HvLpEvent_Rc hvrc;
445         size_t bleft;
446         size_t curlen;
447         const char *curbuf;
448         unsigned long flags;
449         int copy_needed = (viochar == NULL);
450
451         /*
452          * Write to the hvlog of inbound data are now done prior to
453          * calling internal_write() since internal_write() is only called in
454          * the event that an lp event path is active, which isn't the case for
455          * logging attempts prior to console initialization.
456          *
457          * If there is already data queued for this port, send it prior to
458          * attempting to send any new data.
459          */
460         if (pi->used)
461                 send_buffers(pi);
462
463         spin_lock_irqsave(&consolelock, flags);
464
465         /*
466          * If the internal_write() was passed a pointer to a
467          * viocharlpevent then we don't need to allocate a new one
468          * (this is the case where we are internal_writing user space
469          * data).  If we aren't writing user space data then we need
470          * to get an event from viopath.
471          */
472         if (copy_needed) {
473                 /* This one is fetched from the viopath data structure */
474                 viochar = (struct viocharlpevent *)
475                         vio_get_event_buffer(viomajorsubtype_chario);
476                 /* Make sure we got a buffer */
477                 if (viochar == NULL) {
478                         spin_unlock_irqrestore(&consolelock, flags);
479                         hvlog("\n\rviocons: Can't get viochar buffer in internal_write().");
480                         return -EAGAIN;
481                 }
482                 initDataEvent(viochar, pi->lp);
483         }
484
485         curbuf = buf;
486         bleft = len;
487
488         while ((bleft > 0) && (pi->used == 0) &&
489                ((pi->seq - pi->ack) < VIOCHAR_WINDOW)) {
490                 if (bleft > VIOCHAR_MAX_DATA)
491                         curlen = VIOCHAR_MAX_DATA;
492                 else
493                         curlen = bleft;
494
495                 viochar->event.xCorrelationToken = pi->seq++;
496
497                 if (copy_needed) {
498                         memcpy(viochar->data, curbuf, curlen);
499                         viochar->len = curlen;
500                 }
501
502                 viochar->event.xSizeMinus1 =
503                     offsetof(struct viocharlpevent, data) + curlen;
504
505                 hvrc = HvCallEvent_signalLpEvent(&viochar->event);
506                 if (hvrc) {
507                         spin_unlock_irqrestore(&consolelock, flags);
508                         if (copy_needed)
509                                 vio_free_event_buffer(viomajorsubtype_chario, viochar);
510
511                         hvlog("viocons: error sending event! %d\n", (int)hvrc);
512                         return len - bleft;
513                 }
514
515                 curbuf += curlen;
516                 bleft -= curlen;
517         }
518
519         /* If we didn't send it all, buffer as much of it as we can. */
520         if (bleft > 0)
521                 bleft -= buffer_add(pi, curbuf, bleft);
522         /*
523          * Since we grabbed it from the viopath data structure, return
524          * it to the data structure.
525          */
526         if (copy_needed)
527                 vio_free_event_buffer(viomajorsubtype_chario, viochar);
528         spin_unlock_irqrestore(&consolelock, flags);
529
530         return len - bleft;
531 }
532
533 static struct port_info *get_port_data(struct tty_struct *tty)
534 {
535         unsigned long flags;
536         struct port_info *pi;
537
538         spin_lock_irqsave(&consolelock, flags);
539         if (tty) {
540                 pi = (struct port_info *)tty->driver_data;
541                 if (!pi || viotty_paranoia_check(pi, tty->name,
542                                              "get_port_data")) {
543                         pi = NULL;
544                 }
545         } else
546                 /*
547                  * If this is the console device, use the lp from
548                  * the first port entry
549                  */
550                 pi = &port_info[0];
551         spin_unlock_irqrestore(&consolelock, flags);
552         return pi;
553 }
554
555 /*
556  * Initialize the common fields in a charLpEvent
557  */
558 static void initDataEvent(struct viocharlpevent *viochar, HvLpIndex lp)
559 {
560         memset(viochar, 0, sizeof(struct viocharlpevent));
561
562         viochar->event.xFlags.xValid = 1;
563         viochar->event.xFlags.xFunction = HvLpEvent_Function_Int;
564         viochar->event.xFlags.xAckInd = HvLpEvent_AckInd_NoAck;
565         viochar->event.xFlags.xAckType = HvLpEvent_AckType_DeferredAck;
566         viochar->event.xType = HvLpEvent_Type_VirtualIo;
567         viochar->event.xSubtype = viomajorsubtype_chario | viochardata;
568         viochar->event.xSourceLp = HvLpConfig_getLpIndex();
569         viochar->event.xTargetLp = lp;
570         viochar->event.xSizeMinus1 = sizeof(struct viocharlpevent);
571         viochar->event.xSourceInstanceId = viopath_sourceinst(lp);
572         viochar->event.xTargetInstanceId = viopath_targetinst(lp);
573 }
574
575 /*
576  * early console device write
577  */
578 static void viocons_write_early(struct console *co, const char *s, unsigned count)
579 {
580         hvlogOutput(s, count);
581 }
582
583 /*
584  * console device write
585  */
586 static void viocons_write(struct console *co, const char *s, unsigned count)
587 {
588         int index;
589         int begin;
590         struct port_info *pi;
591
592         static const char cr = '\r';
593
594         /*
595          * Check port data first because the target LP might be valid but
596          * simply not active, in which case we want to hvlog the output.
597          */
598         pi = get_port_data(NULL);
599         if (pi == NULL) {
600                 hvlog("\n\rviocons_write: unable to get port data.");
601                 return;
602         }
603
604         hvlogOutput(s, count);
605
606         if (!viopath_isactive(pi->lp)) {
607                 /*
608                  * This is a VERY noisy trace message in the case where the
609                  * path manager is not active or in the case where this
610                  * function is called prior to viocons initialization.  It is
611                  * being commented out for the sake of a clear trace buffer.
612                  */
613 #if 0
614                  hvlog("\n\rviocons_write: path not active to lp %d", pi->lp);
615 #endif
616                 return;
617         }
618
619         /* 
620          * Any newline character found will cause a
621          * carriage return character to be emitted as well. 
622          */
623         begin = 0;
624         for (index = 0; index < count; index++) {
625                 if (s[index] == '\n') {
626                         /* 
627                          * Newline found. Print everything up to and 
628                          * including the newline
629                          */
630                         internal_write(pi, &s[begin], index - begin + 1,
631                                         NULL);
632                         begin = index + 1;
633                         /* Emit a carriage return as well */
634                         internal_write(pi, &cr, 1, NULL);
635                 }
636         }
637
638         /* If any characters left to write, write them now */
639         if ((index - begin) > 0)
640                 internal_write(pi, &s[begin], index - begin, NULL);
641 }
642
643 /*
644  * Work out the device associate with this console
645  */
646 static struct tty_driver *viocons_device(struct console *c, int *index)
647 {
648         *index = c->index;
649         return viotty_driver;
650 }
651
652 /*
653  * console device I/O methods
654  */
655 static struct console viocons_early = {
656         .name = "viocons",
657         .write = viocons_write_early,
658         .flags = CON_PRINTBUFFER,
659         .index = -1,
660 };
661
662 static struct console viocons = {
663         .name = "viocons",
664         .write = viocons_write,
665         .device = viocons_device,
666         .flags = CON_PRINTBUFFER,
667         .index = -1,
668 };
669
670 /*
671  * TTY Open method
672  */
673 static int viotty_open(struct tty_struct *tty, struct file *filp)
674 {
675         int port;
676         unsigned long flags;
677         struct port_info *pi;
678
679         port = tty->index;
680
681         if ((port < 0) || (port >= VTTY_PORTS))
682                 return -ENODEV;
683
684         spin_lock_irqsave(&consolelock, flags);
685
686         pi = &port_info[port];
687         /* If some other TTY is already connected here, reject the open */
688         if ((pi->tty) && (pi->tty != tty)) {
689                 spin_unlock_irqrestore(&consolelock, flags);
690                 printk(VIOCONS_KERN_WARN
691                        "attempt to open device twice from different ttys\n");
692                 return -EBUSY;
693         }
694         tty->driver_data = pi;
695         pi->tty = tty;
696         spin_unlock_irqrestore(&consolelock, flags);
697
698         return 0;
699 }
700
701 /*
702  * TTY Close method
703  */
704 static void viotty_close(struct tty_struct *tty, struct file *filp)
705 {
706         unsigned long flags;
707         struct port_info *pi;
708
709         spin_lock_irqsave(&consolelock, flags);
710         pi = (struct port_info *)tty->driver_data;
711
712         if (!pi || viotty_paranoia_check(pi, tty->name, "viotty_close")) {
713                 spin_unlock_irqrestore(&consolelock, flags);
714                 return;
715         }
716         if (tty->count == 1)
717                 pi->tty = NULL;
718         spin_unlock_irqrestore(&consolelock, flags);
719 }
720
721 /*
722  * TTY Write method
723  */
724 static int viotty_write(struct tty_struct *tty, int from_user,
725                         const unsigned char *buf, int count)
726 {
727         int ret;
728         int total = 0;
729         struct port_info *pi;
730
731         pi = get_port_data(tty);
732         if (pi == NULL) {
733                 hvlog("\n\rviotty_write: no port data.");
734                 return -ENODEV;
735         }
736
737         if (viochar_is_console(pi))
738                 hvlogOutput(buf, count);
739
740         /*
741          * If the path to this LP is closed, don't bother doing anything more.
742          * just dump the data on the floor and return count.  For some reason
743          * some user level programs will attempt to probe available tty's and
744          * they'll attempt a viotty_write on an invalid port which maps to an
745          * invalid target lp.  If this is the case then ignore the
746          * viotty_write call and, since the viopath isn't active to this
747          * partition, return count.
748          */
749         if (!viopath_isactive(pi->lp)) {
750                 /* Noisy trace.  Commented unless needed. */
751 #if 0
752                  hvlog("\n\rviotty_write: viopath NOT active for lp %d.",pi->lp);
753 #endif
754                 return count;
755         }
756
757         /*
758          * If the viotty_write is invoked from user space we want to do the
759          * copy_from_user() into an event buffer from the cfu buffer before
760          * internal_write() is called because internal_write may need to buffer
761          * data which will need to grab a spin_lock and we shouldn't
762          * copy_from_user() while holding a spin_lock.  Should internal_write()
763          * not need to buffer data then it'll just use the event we created here
764          * rather than checking one out from vio_get_event_buffer().
765          */
766         if (from_user) {
767                 struct viocharlpevent *viochar;
768                 int curlen;
769                 const char *curbuf = buf;
770
771                 viochar = viocons_get_cfu_buffer();
772                 if (viochar == NULL)
773                         return -EAGAIN;
774                 initDataEvent(viochar, pi->lp);
775                 while (count > 0) {
776                         if (count > VIOCHAR_MAX_DATA)
777                                 curlen = VIOCHAR_MAX_DATA;
778                         else
779                                 curlen = count;
780                         viochar->len = curlen;
781                         ret = copy_from_user(viochar->data, curbuf, curlen);
782                         if (ret)
783                                 break;
784                         ret = internal_write(pi, viochar->data,
785                                         viochar->len, viochar);
786                         total += ret;
787                         if (ret != curlen)
788                                 break;
789                         count -= curlen;
790                         curbuf += curlen;
791                 }
792                 viocons_free_cfu_buffer(viochar);
793         } else
794                 total = internal_write(pi, buf, count, NULL);
795         return total;
796 }
797
798 /*
799  * TTY put_char method
800  */
801 static void viotty_put_char(struct tty_struct *tty, unsigned char ch)
802 {
803         struct port_info *pi;
804
805         pi = get_port_data(tty);
806         if (pi == NULL)
807                 return;
808
809         /* This will append '\r' as well if the char is '\n' */
810         if (viochar_is_console(pi))
811                 hvlogOutput(&ch, 1);
812
813         if (viopath_isactive(pi->lp))
814                 internal_write(pi, &ch, 1, NULL);
815 }
816
817 /*
818  * TTY write_room method
819  */
820 static int viotty_write_room(struct tty_struct *tty)
821 {
822         int i;
823         int room = 0;
824         struct port_info *pi;
825         unsigned long flags;
826
827         spin_lock_irqsave(&consolelock, flags);
828         pi = (struct port_info *)tty->driver_data;
829         if (!pi || viotty_paranoia_check(pi, tty->name, "viotty_write_room")) {
830                 spin_unlock_irqrestore(&consolelock, flags);
831                 return 0;
832         }
833
834         /* If no buffers are used, return the max size. */
835         if (pi->used == 0) {
836                 spin_unlock_irqrestore(&consolelock, flags);
837                 return VIOCHAR_MAX_DATA * VIOCHAR_NUM_BUF;
838         }
839
840         /*
841          * We retain the spinlock because we want to get an accurate
842          * count and it can change on us between each operation if we
843          * don't hold the spinlock.
844          */
845         for (i = 0; ((i < VIOCHAR_NUM_BUF) && (room < VIOCHAR_MAX_DATA)); i++)
846                 room += (VIOCHAR_MAX_DATA - pi->bufferBytes[i]);
847         spin_unlock_irqrestore(&consolelock, flags);
848
849         if (room > VIOCHAR_MAX_DATA)
850                 room = VIOCHAR_MAX_DATA;
851         return room;
852 }
853
854 /*
855  * TTY chars_in_buffer method
856  */
857 static int viotty_chars_in_buffer(struct tty_struct *tty)
858 {
859         return 0;
860 }
861
862 static int viotty_ioctl(struct tty_struct *tty, struct file *file,
863                         unsigned int cmd, unsigned long arg)
864 {
865         switch (cmd) {
866         /*
867          * the ioctls below read/set the flags usually shown in the leds
868          * don't use them - they will go away without warning
869          */
870         case KDGETLED:
871         case KDGKBLED:
872                 return put_user(0, (char *)arg);
873
874         case KDSKBLED:
875                 return 0;
876         }
877
878         return n_tty_ioctl(tty, file, cmd, arg);
879 }
880
881 /*
882  * Handle an open charLpEvent.  Could be either interrupt or ack
883  */
884 static void vioHandleOpenEvent(struct HvLpEvent *event)
885 {
886         unsigned long flags;
887         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
888         u8 port = cevent->virtual_device;
889         struct port_info *pi;
890         int reject = 0;
891
892         if (event->xFlags.xFunction == HvLpEvent_Function_Ack) {
893                 if (port >= VTTY_PORTS)
894                         return;
895
896                 spin_lock_irqsave(&consolelock, flags);
897                 /* Got the lock, don't cause console output */
898
899                 pi = &port_info[port];
900                 if (event->xRc == HvLpEvent_Rc_Good) {
901                         pi->seq = pi->ack = 0;
902                         /*
903                          * This line allows connections from the primary
904                          * partition but once one is connected from the
905                          * primary partition nothing short of a reboot
906                          * of linux will allow access from the hosting
907                          * partition again without a required iSeries fix.
908                          */
909                         pi->lp = event->xTargetLp;
910                 }
911
912                 spin_unlock_irqrestore(&consolelock, flags);
913                 if (event->xRc != HvLpEvent_Rc_Good)
914                         printk(VIOCONS_KERN_WARN
915                                "handle_open_event: event->xRc == (%d).\n",
916                                event->xRc);
917
918                 if (event->xCorrelationToken != 0) {
919                         atomic_t *aptr= (atomic_t *)event->xCorrelationToken;
920                         atomic_set(aptr, 1);
921                 } else
922                         printk(VIOCONS_KERN_WARN
923                                "wierd...got open ack without atomic\n");
924                 return;
925         }
926
927         /* This had better require an ack, otherwise complain */
928         if (event->xFlags.xAckInd != HvLpEvent_AckInd_DoAck) {
929                 printk(VIOCONS_KERN_WARN "viocharopen without ack bit!\n");
930                 return;
931         }
932
933         spin_lock_irqsave(&consolelock, flags);
934         /* Got the lock, don't cause console output */
935
936         /* Make sure this is a good virtual tty */
937         if (port >= VTTY_PORTS) {
938                 event->xRc = HvLpEvent_Rc_SubtypeError;
939                 cevent->subtype_result_code = viorc_openRejected;
940                 /*
941                  * Flag state here since we can't printk while holding
942                  * a spinlock.
943                  */
944                 reject = 1;
945         } else {
946                 pi = &port_info[port];
947                 if ((pi->lp != HvLpIndexInvalid) &&
948                                 (pi->lp != event->xSourceLp)) {
949                         /*
950                          * If this is tty is already connected to a different
951                          * partition, fail.
952                          */
953                         event->xRc = HvLpEvent_Rc_SubtypeError;
954                         cevent->subtype_result_code = viorc_openRejected;
955                         reject = 2;
956                 } else {
957                         pi->lp = event->xSourceLp;
958                         event->xRc = HvLpEvent_Rc_Good;
959                         cevent->subtype_result_code = viorc_good;
960                         pi->seq = pi->ack = 0;
961                         reject = 0;
962                 }
963         }
964
965         spin_unlock_irqrestore(&consolelock, flags);
966
967         if (reject == 1)
968                 printk(VIOCONS_KERN_WARN "open rejected: bad virtual tty.\n");
969         else if (reject == 2)
970                 printk(VIOCONS_KERN_WARN
971                         "open rejected: console in exclusive use by another partition.\n");
972
973         /* Return the acknowledgement */
974         HvCallEvent_ackLpEvent(event);
975 }
976
977 /*
978  * Handle a close charLpEvent.  This should ONLY be an Interrupt because the
979  * virtual console should never actually issue a close event to the hypervisor
980  * because the virtual console never goes away.  A close event coming from the
981  * hypervisor simply means that there are no client consoles connected to the
982  * virtual console.
983  *
984  * Regardless of the number of connections masqueraded on the other side of
985  * the hypervisor ONLY ONE close event should be called to accompany the ONE
986  * open event that is called.  The close event should ONLY be called when NO
987  * MORE connections (masqueraded or not) exist on the other side of the
988  * hypervisor.
989  */
990 static void vioHandleCloseEvent(struct HvLpEvent *event)
991 {
992         unsigned long flags;
993         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
994         u8 port = cevent->virtual_device;
995
996         if (event->xFlags.xFunction == HvLpEvent_Function_Int) {
997                 if (port >= VTTY_PORTS) {
998                         printk(VIOCONS_KERN_WARN
999                                         "close message from invalid virtual device.\n");
1000                         return;
1001                 }
1002
1003                 /* For closes, just mark the console partition invalid */
1004                 spin_lock_irqsave(&consolelock, flags);
1005                 /* Got the lock, don't cause console output */
1006
1007                 if (port_info[port].lp == event->xSourceLp)
1008                         port_info[port].lp = HvLpIndexInvalid;
1009
1010                 spin_unlock_irqrestore(&consolelock, flags);
1011                 printk(VIOCONS_KERN_INFO "close from %d\n", event->xSourceLp);
1012         } else
1013                 printk(VIOCONS_KERN_WARN
1014                                 "got unexpected close acknowlegement\n");
1015 }
1016
1017 /*
1018  * Handle a config charLpEvent.  Could be either interrupt or ack
1019  */
1020 static void vioHandleConfig(struct HvLpEvent *event)
1021 {
1022         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
1023
1024         HvCall_writeLogBuffer(cevent->data, cevent->len);
1025
1026         if (cevent->data[0] == 0x01)
1027                 printk(VIOCONS_KERN_INFO "window resized to %d: %d: %d: %d\n",
1028                        cevent->data[1], cevent->data[2],
1029                        cevent->data[3], cevent->data[4]);
1030         else
1031                 printk(VIOCONS_KERN_WARN "unknown config event\n");
1032 }
1033
1034 /*
1035  * Handle a data charLpEvent. 
1036  */
1037 static void vioHandleData(struct HvLpEvent *event)
1038 {
1039         struct tty_struct *tty;
1040         unsigned long flags;
1041         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
1042         struct port_info *pi;
1043         int index;
1044         u8 port = cevent->virtual_device;
1045
1046         if (port >= VTTY_PORTS) {
1047                 printk(VIOCONS_KERN_WARN "data on invalid virtual device %d\n",
1048                                 port);
1049                 return;
1050         }
1051
1052         /*
1053          * Hold the spinlock so that we don't take an interrupt that
1054          * changes tty between the time we fetch the port_info
1055          * pointer and the time we paranoia check.
1056          */
1057         spin_lock_irqsave(&consolelock, flags);
1058         pi = &port_info[port];
1059
1060         /*
1061          * Change 05/01/2003 - Ryan Arnold: If a partition other than
1062          * the current exclusive partition tries to send us data
1063          * events then just drop them on the floor because we don't
1064          * want his stinking data.  He isn't authorized to receive
1065          * data because he wasn't the first one to get the console,
1066          * therefore he shouldn't be allowed to send data either.
1067          * This will work without an iSeries fix.
1068          */
1069         if (pi->lp != event->xSourceLp) {
1070                 spin_unlock_irqrestore(&consolelock, flags);
1071                 return;
1072         }
1073
1074         tty = pi->tty;
1075         if (tty == NULL) {
1076                 spin_unlock_irqrestore(&consolelock, flags);
1077                 printk(VIOCONS_KERN_WARN "no tty for virtual device %d\n",
1078                                 port);
1079                 return;
1080         }
1081
1082         if (tty->magic != TTY_MAGIC) {
1083                 spin_unlock_irqrestore(&consolelock, flags);
1084                 printk(VIOCONS_KERN_WARN "tty bad magic\n");
1085                 return;
1086         }
1087
1088         /*
1089          * Just to be paranoid, make sure the tty points back to this port
1090          */
1091         pi = (struct port_info *)tty->driver_data;
1092         if (!pi || viotty_paranoia_check(pi, tty->name, "vioHandleData")) {
1093                 spin_unlock_irqrestore(&consolelock, flags);
1094                 return;
1095         }
1096         spin_unlock_irqrestore(&consolelock, flags);
1097
1098         /*
1099          * Change 07/21/2003 - Ryan Arnold: functionality added to
1100          * support sysrq utilizing ^O as the sysrq key.  The sysrq
1101          * functionality will only work if built into the kernel and
1102          * then only if sysrq is enabled through the proc filesystem.
1103          */
1104         for (index = 0; index < cevent->len; index++) {
1105 #ifdef CONFIG_MAGIC_SYSRQ
1106                 if (sysrq_enabled) {
1107                         /* 0x0f is the ascii character for ^O */
1108                         if (cevent->data[index] == '\x0f') {
1109                                 vio_sysrq_pressed = 1;
1110                                 /*
1111                                  * continue because we don't want to add
1112                                  * the sysrq key into the data string.
1113                                  */
1114                                 continue;
1115                         } else if (vio_sysrq_pressed) {
1116                                 handle_sysrq(cevent->data[index], NULL, tty);
1117                                 vio_sysrq_pressed = 0;
1118                                 /*
1119                                  * continue because we don't want to add
1120                                  * the sysrq sequence into the data string.
1121                                  */
1122                                 continue;
1123                         }
1124                 }
1125 #endif
1126                 /*
1127                  * The sysrq sequence isn't included in this check if
1128                  * sysrq is enabled and compiled into the kernel because
1129                  * the sequence will never get inserted into the buffer.
1130                  * Don't attempt to copy more data into the buffer than we
1131                  * have room for because it would fail without indication.
1132                  */
1133                 if ((tty->flip.count + 1) > TTY_FLIPBUF_SIZE) {
1134                         printk(VIOCONS_KERN_WARN "input buffer overflow!\n");
1135                         break;
1136                 }
1137                 tty_insert_flip_char(tty, cevent->data[index], TTY_NORMAL);
1138         }
1139
1140         /* if cevent->len == 0 then no data was added to the buffer and flip.count == 0 */
1141         if (tty->flip.count)
1142                 /* The next call resets flip.count when the data is flushed. */
1143                 tty_flip_buffer_push(tty);
1144 }
1145
1146 /*
1147  * Handle an ack charLpEvent. 
1148  */
1149 static void vioHandleAck(struct HvLpEvent *event)
1150 {
1151         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
1152         unsigned long flags;
1153         u8 port = cevent->virtual_device;
1154
1155         if (port >= VTTY_PORTS) {
1156                 printk(VIOCONS_KERN_WARN "data on invalid virtual device\n");
1157                 return;
1158         }
1159
1160         spin_lock_irqsave(&consolelock, flags);
1161         port_info[port].ack = event->xCorrelationToken;
1162         spin_unlock_irqrestore(&consolelock, flags);
1163
1164         if (port_info[port].used)
1165                 send_buffers(&port_info[port]);
1166 }
1167
1168 /*
1169  * Handle charLpEvents and route to the appropriate routine
1170  */
1171 static void vioHandleCharEvent(struct HvLpEvent *event)
1172 {
1173         int charminor;
1174
1175         if (event == NULL)
1176                 return;
1177
1178         charminor = event->xSubtype & VIOMINOR_SUBTYPE_MASK;
1179         switch (charminor) {
1180         case viocharopen:
1181                 vioHandleOpenEvent(event);
1182                 break;
1183         case viocharclose:
1184                 vioHandleCloseEvent(event);
1185                 break;
1186         case viochardata:
1187                 vioHandleData(event);
1188                 break;
1189         case viocharack:
1190                 vioHandleAck(event);
1191                 break;
1192         case viocharconfig:
1193                 vioHandleConfig(event);
1194                 break;
1195         default:
1196                 if ((event->xFlags.xFunction == HvLpEvent_Function_Int) &&
1197                     (event->xFlags.xAckInd == HvLpEvent_AckInd_DoAck)) {
1198                         event->xRc = HvLpEvent_Rc_InvalidSubtype;
1199                         HvCallEvent_ackLpEvent(event);
1200                 }
1201         }
1202 }
1203
1204 /*
1205  * Send an open event
1206  */
1207 static int send_open(HvLpIndex remoteLp, void *sem)
1208 {
1209         return HvCallEvent_signalLpEventFast(remoteLp,
1210                         HvLpEvent_Type_VirtualIo,
1211                         viomajorsubtype_chario | viocharopen,
1212                         HvLpEvent_AckInd_DoAck, HvLpEvent_AckType_ImmediateAck,
1213                         viopath_sourceinst(remoteLp),
1214                         viopath_targetinst(remoteLp),
1215                         (u64)(unsigned long)sem, VIOVERSION << 16,
1216                         0, 0, 0, 0);
1217 }
1218
1219 static struct tty_operations serial_ops = {
1220         .open = viotty_open,
1221         .close = viotty_close,
1222         .write = viotty_write,
1223         .put_char = viotty_put_char,
1224         .write_room = viotty_write_room,
1225         .chars_in_buffer = viotty_chars_in_buffer,
1226         .ioctl = viotty_ioctl,
1227 };
1228
1229 static int __init viocons_init2(void)
1230 {
1231         atomic_t wait_flag;
1232         int rc;
1233
1234         /* +2 for fudge */
1235         rc = viopath_open(HvLpConfig_getPrimaryLpIndex(),
1236                         viomajorsubtype_chario, VIOCHAR_WINDOW + 2);
1237         if (rc)
1238                 printk(VIOCONS_KERN_WARN "error opening to primary %d\n", rc);
1239
1240         if (viopath_hostLp == HvLpIndexInvalid)
1241                 vio_set_hostlp();
1242
1243         /*
1244          * And if the primary is not the same as the hosting LP, open to the 
1245          * hosting lp
1246          */
1247         if ((viopath_hostLp != HvLpIndexInvalid) &&
1248             (viopath_hostLp != HvLpConfig_getPrimaryLpIndex())) {
1249                 printk(VIOCONS_KERN_INFO "open path to hosting (%d)\n",
1250                                 viopath_hostLp);
1251                 rc = viopath_open(viopath_hostLp, viomajorsubtype_chario,
1252                                 VIOCHAR_WINDOW + 2);    /* +2 for fudge */
1253                 if (rc)
1254                         printk(VIOCONS_KERN_WARN
1255                                 "error opening to partition %d: %d\n",
1256                                 viopath_hostLp, rc);
1257         }
1258
1259         if (vio_setHandler(viomajorsubtype_chario, vioHandleCharEvent) < 0)
1260                 printk(VIOCONS_KERN_WARN
1261                                 "error seting handler for console events!\n");
1262
1263         /*
1264          * First, try to open the console to the hosting lp.
1265          * Wait on a semaphore for the response.
1266          */
1267         atomic_set(&wait_flag, 0);
1268         if ((viopath_isactive(viopath_hostLp)) &&
1269             (send_open(viopath_hostLp, (void *)&wait_flag) == 0)) {
1270                 printk(VIOCONS_KERN_INFO "hosting partition %d\n",
1271                         viopath_hostLp);
1272                 while (atomic_read(&wait_flag) == 0)
1273                         mb();
1274                 atomic_set(&wait_flag, 0);
1275         }
1276
1277         /*
1278          * If we don't have an active console, try the primary
1279          */
1280         if ((!viopath_isactive(port_info[0].lp)) &&
1281             (viopath_isactive(HvLpConfig_getPrimaryLpIndex())) &&
1282             (send_open(HvLpConfig_getPrimaryLpIndex(), (void *)&wait_flag)
1283              == 0)) {
1284                 printk(VIOCONS_KERN_INFO "opening console to primary partition\n");
1285                 while (atomic_read(&wait_flag) == 0)
1286                         mb();
1287         }
1288
1289         /* Initialize the tty_driver structure */
1290         viotty_driver = alloc_tty_driver(VTTY_PORTS);
1291         viotty_driver->owner = THIS_MODULE;
1292         viotty_driver->driver_name = "vioconsole";
1293         viotty_driver->devfs_name = "vcs/";
1294         viotty_driver->name = "tty";
1295         viotty_driver->name_base = 1;
1296         viotty_driver->major = TTY_MAJOR;
1297         viotty_driver->minor_start = 1;
1298         viotty_driver->type = TTY_DRIVER_TYPE_CONSOLE;
1299         viotty_driver->subtype = 1;
1300         viotty_driver->init_termios = tty_std_termios;
1301         viotty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_RESET_TERMIOS;
1302         tty_set_operations(viotty_driver, &serial_ops);
1303
1304         if (tty_register_driver(viotty_driver)) {
1305                 printk(VIOCONS_KERN_WARN "couldn't register console driver\n");
1306                 put_tty_driver(viotty_driver);
1307                 viotty_driver = NULL;
1308         }
1309
1310         viocons_init_cfu_buffer();
1311
1312         unregister_console(&viocons_early);
1313         register_console(&viocons);
1314
1315         return 0;
1316 }
1317
1318 static int __init viocons_init(void)
1319 {
1320         int i;
1321
1322         printk(VIOCONS_KERN_INFO "registering console\n");
1323         for (i = 0; i < VTTY_PORTS; i++) {
1324                 port_info[i].lp = HvLpIndexInvalid;
1325                 port_info[i].magic = VIOTTY_MAGIC;
1326         }
1327         HvCall_setLogBufferFormatAndCodepage(HvCall_LogBuffer_ASCII, 437);
1328         register_console(&viocons_early);
1329         return 0;
1330 }
1331
1332 console_initcall(viocons_init);
1333 module_init(viocons_init2);