ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[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                         if ((pi->tty->flags & (1 << TTY_DO_WRITE_WAKEUP)) &&
426                             (pi->tty->ldisc.write_wakeup))
427                                 (pi->tty->ldisc.write_wakeup)(pi->tty);
428                         wake_up_interruptible(&pi->tty->write_wait);
429                 }
430         }
431
432         vio_free_event_buffer(viomajorsubtype_chario, viochar);
433         spin_unlock_irqrestore(&consolelock, flags);
434 }
435
436 /*
437  * Our internal writer.  Gets called both from the console device and
438  * the tty device.  the tty pointer will be NULL if called from the console.
439  * Return total number of bytes "written".
440  *
441  * NOTE: Don't use printk in here because it gets nastily recursive.  hvlog
442  * can be used to log to the hypervisor buffer
443  */
444 static int internal_write(struct port_info *pi, const char *buf,
445                           size_t len, struct viocharlpevent *viochar)
446 {
447         HvLpEvent_Rc hvrc;
448         size_t bleft;
449         size_t curlen;
450         const char *curbuf;
451         unsigned long flags;
452         int copy_needed = (viochar == NULL);
453
454         /*
455          * Write to the hvlog of inbound data are now done prior to
456          * calling internal_write() since internal_write() is only called in
457          * the event that an lp event path is active, which isn't the case for
458          * logging attempts prior to console initialization.
459          *
460          * If there is already data queued for this port, send it prior to
461          * attempting to send any new data.
462          */
463         if (pi->used)
464                 send_buffers(pi);
465
466         spin_lock_irqsave(&consolelock, flags);
467
468         /*
469          * If the internal_write() was passed a pointer to a
470          * viocharlpevent then we don't need to allocate a new one
471          * (this is the case where we are internal_writing user space
472          * data).  If we aren't writing user space data then we need
473          * to get an event from viopath.
474          */
475         if (copy_needed) {
476                 /* This one is fetched from the viopath data structure */
477                 viochar = (struct viocharlpevent *)
478                         vio_get_event_buffer(viomajorsubtype_chario);
479                 /* Make sure we got a buffer */
480                 if (viochar == NULL) {
481                         spin_unlock_irqrestore(&consolelock, flags);
482                         hvlog("\n\rviocons: Can't get viochar buffer in internal_write().");
483                         return -EAGAIN;
484                 }
485                 initDataEvent(viochar, pi->lp);
486         }
487
488         curbuf = buf;
489         bleft = len;
490
491         while ((bleft > 0) && (pi->used == 0) &&
492                ((pi->seq - pi->ack) < VIOCHAR_WINDOW)) {
493                 if (bleft > VIOCHAR_MAX_DATA)
494                         curlen = VIOCHAR_MAX_DATA;
495                 else
496                         curlen = bleft;
497
498                 viochar->event.xCorrelationToken = pi->seq++;
499
500                 if (copy_needed) {
501                         memcpy(viochar->data, curbuf, curlen);
502                         viochar->len = curlen;
503                 }
504
505                 viochar->event.xSizeMinus1 =
506                     offsetof(struct viocharlpevent, data) + curlen;
507
508                 hvrc = HvCallEvent_signalLpEvent(&viochar->event);
509                 if (hvrc) {
510                         spin_unlock_irqrestore(&consolelock, flags);
511                         if (copy_needed)
512                                 vio_free_event_buffer(viomajorsubtype_chario, viochar);
513
514                         hvlog("viocons: error sending event! %d\n", (int)hvrc);
515                         return len - bleft;
516                 }
517
518                 curbuf += curlen;
519                 bleft -= curlen;
520         }
521
522         /* If we didn't send it all, buffer as much of it as we can. */
523         if (bleft > 0)
524                 bleft -= buffer_add(pi, curbuf, bleft);
525         /*
526          * Since we grabbed it from the viopath data structure, return
527          * it to the data structure.
528          */
529         if (copy_needed)
530                 vio_free_event_buffer(viomajorsubtype_chario, viochar);
531         spin_unlock_irqrestore(&consolelock, flags);
532
533         return len - bleft;
534 }
535
536 static struct port_info *get_port_data(struct tty_struct *tty)
537 {
538         unsigned long flags;
539         struct port_info *pi;
540
541         spin_lock_irqsave(&consolelock, flags);
542         if (tty) {
543                 pi = (struct port_info *)tty->driver_data;
544                 if (!pi || viotty_paranoia_check(pi, tty->name,
545                                              "get_port_data")) {
546                         pi = NULL;
547                 }
548         } else
549                 /*
550                  * If this is the console device, use the lp from
551                  * the first port entry
552                  */
553                 pi = &port_info[0];
554         spin_unlock_irqrestore(&consolelock, flags);
555         return pi;
556 }
557
558 /*
559  * Initialize the common fields in a charLpEvent
560  */
561 static void initDataEvent(struct viocharlpevent *viochar, HvLpIndex lp)
562 {
563         memset(viochar, 0, sizeof(struct viocharlpevent));
564
565         viochar->event.xFlags.xValid = 1;
566         viochar->event.xFlags.xFunction = HvLpEvent_Function_Int;
567         viochar->event.xFlags.xAckInd = HvLpEvent_AckInd_NoAck;
568         viochar->event.xFlags.xAckType = HvLpEvent_AckType_DeferredAck;
569         viochar->event.xType = HvLpEvent_Type_VirtualIo;
570         viochar->event.xSubtype = viomajorsubtype_chario | viochardata;
571         viochar->event.xSourceLp = HvLpConfig_getLpIndex();
572         viochar->event.xTargetLp = lp;
573         viochar->event.xSizeMinus1 = sizeof(struct viocharlpevent);
574         viochar->event.xSourceInstanceId = viopath_sourceinst(lp);
575         viochar->event.xTargetInstanceId = viopath_targetinst(lp);
576 }
577
578 /*
579  * early console device write
580  */
581 static void viocons_write_early(struct console *co, const char *s, unsigned count)
582 {
583         hvlogOutput(s, count);
584 }
585
586 /*
587  * console device write
588  */
589 static void viocons_write(struct console *co, const char *s, unsigned count)
590 {
591         int index;
592         int begin;
593         struct port_info *pi;
594
595         static const char cr = '\r';
596
597         /*
598          * Check port data first because the target LP might be valid but
599          * simply not active, in which case we want to hvlog the output.
600          */
601         pi = get_port_data(NULL);
602         if (pi == NULL) {
603                 hvlog("\n\rviocons_write: unable to get port data.");
604                 return;
605         }
606
607         hvlogOutput(s, count);
608
609         if (!viopath_isactive(pi->lp)) {
610                 /*
611                  * This is a VERY noisy trace message in the case where the
612                  * path manager is not active or in the case where this
613                  * function is called prior to viocons initialization.  It is
614                  * being commented out for the sake of a clear trace buffer.
615                  */
616 #if 0
617                  hvlog("\n\rviocons_write: path not active to lp %d", pi->lp);
618 #endif
619                 return;
620         }
621
622         /* 
623          * Any newline character found will cause a
624          * carriage return character to be emitted as well. 
625          */
626         begin = 0;
627         for (index = 0; index < count; index++) {
628                 if (s[index] == '\n') {
629                         /* 
630                          * Newline found. Print everything up to and 
631                          * including the newline
632                          */
633                         internal_write(pi, &s[begin], index - begin + 1,
634                                         NULL);
635                         begin = index + 1;
636                         /* Emit a carriage return as well */
637                         internal_write(pi, &cr, 1, NULL);
638                 }
639         }
640
641         /* If any characters left to write, write them now */
642         if ((index - begin) > 0)
643                 internal_write(pi, &s[begin], index - begin, NULL);
644 }
645
646 /*
647  * Work out the device associate with this console
648  */
649 static struct tty_driver *viocons_device(struct console *c, int *index)
650 {
651         *index = c->index;
652         return viotty_driver;
653 }
654
655 /*
656  * console device I/O methods
657  */
658 static struct console viocons_early = {
659         .name = "viocons",
660         .write = viocons_write_early,
661         .flags = CON_PRINTBUFFER,
662         .index = -1,
663 };
664
665 static struct console viocons = {
666         .name = "viocons",
667         .write = viocons_write,
668         .device = viocons_device,
669         .flags = CON_PRINTBUFFER,
670         .index = -1,
671 };
672
673 /*
674  * TTY Open method
675  */
676 static int viotty_open(struct tty_struct *tty, struct file *filp)
677 {
678         int port;
679         unsigned long flags;
680         struct port_info *pi;
681
682         port = tty->index;
683
684         if ((port < 0) || (port >= VTTY_PORTS))
685                 return -ENODEV;
686
687         spin_lock_irqsave(&consolelock, flags);
688
689         pi = &port_info[port];
690         /* If some other TTY is already connected here, reject the open */
691         if ((pi->tty) && (pi->tty != tty)) {
692                 spin_unlock_irqrestore(&consolelock, flags);
693                 printk(VIOCONS_KERN_WARN
694                        "attempt to open device twice from different ttys\n");
695                 return -EBUSY;
696         }
697         tty->driver_data = pi;
698         pi->tty = tty;
699         spin_unlock_irqrestore(&consolelock, flags);
700
701         return 0;
702 }
703
704 /*
705  * TTY Close method
706  */
707 static void viotty_close(struct tty_struct *tty, struct file *filp)
708 {
709         unsigned long flags;
710         struct port_info *pi;
711
712         spin_lock_irqsave(&consolelock, flags);
713         pi = (struct port_info *)tty->driver_data;
714
715         if (!pi || viotty_paranoia_check(pi, tty->name, "viotty_close")) {
716                 spin_unlock_irqrestore(&consolelock, flags);
717                 return;
718         }
719         if (tty->count == 1)
720                 pi->tty = NULL;
721         spin_unlock_irqrestore(&consolelock, flags);
722 }
723
724 /*
725  * TTY Write method
726  */
727 static int viotty_write(struct tty_struct *tty, int from_user,
728                         const unsigned char *buf, int count)
729 {
730         int ret;
731         int total = 0;
732         struct port_info *pi;
733
734         pi = get_port_data(tty);
735         if (pi == NULL) {
736                 hvlog("\n\rviotty_write: no port data.");
737                 return -ENODEV;
738         }
739
740         if (viochar_is_console(pi))
741                 hvlogOutput(buf, count);
742
743         /*
744          * If the path to this LP is closed, don't bother doing anything more.
745          * just dump the data on the floor and return count.  For some reason
746          * some user level programs will attempt to probe available tty's and
747          * they'll attempt a viotty_write on an invalid port which maps to an
748          * invalid target lp.  If this is the case then ignore the
749          * viotty_write call and, since the viopath isn't active to this
750          * partition, return count.
751          */
752         if (!viopath_isactive(pi->lp)) {
753                 /* Noisy trace.  Commented unless needed. */
754 #if 0
755                  hvlog("\n\rviotty_write: viopath NOT active for lp %d.",pi->lp);
756 #endif
757                 return count;
758         }
759
760         /*
761          * If the viotty_write is invoked from user space we want to do the
762          * copy_from_user() into an event buffer from the cfu buffer before
763          * internal_write() is called because internal_write may need to buffer
764          * data which will need to grab a spin_lock and we shouldn't
765          * copy_from_user() while holding a spin_lock.  Should internal_write()
766          * not need to buffer data then it'll just use the event we created here
767          * rather than checking one out from vio_get_event_buffer().
768          */
769         if (from_user) {
770                 struct viocharlpevent *viochar;
771                 int curlen;
772                 const char *curbuf = buf;
773
774                 viochar = viocons_get_cfu_buffer();
775                 if (viochar == NULL)
776                         return -EAGAIN;
777                 initDataEvent(viochar, pi->lp);
778                 while (count > 0) {
779                         if (count > VIOCHAR_MAX_DATA)
780                                 curlen = VIOCHAR_MAX_DATA;
781                         else
782                                 curlen = count;
783                         viochar->len = curlen;
784                         ret = copy_from_user(viochar->data, curbuf, curlen);
785                         if (ret)
786                                 break;
787                         ret = internal_write(pi, viochar->data,
788                                         viochar->len, viochar);
789                         total += ret;
790                         if (ret != curlen)
791                                 break;
792                         count -= curlen;
793                         curbuf += curlen;
794                 }
795                 viocons_free_cfu_buffer(viochar);
796         } else
797                 total = internal_write(pi, buf, count, NULL);
798         return total;
799 }
800
801 /*
802  * TTY put_char method
803  */
804 static void viotty_put_char(struct tty_struct *tty, unsigned char ch)
805 {
806         struct port_info *pi;
807
808         pi = get_port_data(tty);
809         if (pi == NULL)
810                 return;
811
812         /* This will append '\r' as well if the char is '\n' */
813         if (viochar_is_console(pi))
814                 hvlogOutput(&ch, 1);
815
816         if (viopath_isactive(pi->lp))
817                 internal_write(pi, &ch, 1, NULL);
818 }
819
820 /*
821  * TTY write_room method
822  */
823 static int viotty_write_room(struct tty_struct *tty)
824 {
825         int i;
826         int room = 0;
827         struct port_info *pi;
828         unsigned long flags;
829
830         spin_lock_irqsave(&consolelock, flags);
831         pi = (struct port_info *)tty->driver_data;
832         if (!pi || viotty_paranoia_check(pi, tty->name, "viotty_write_room")) {
833                 spin_unlock_irqrestore(&consolelock, flags);
834                 return 0;
835         }
836
837         /* If no buffers are used, return the max size. */
838         if (pi->used == 0) {
839                 spin_unlock_irqrestore(&consolelock, flags);
840                 return VIOCHAR_MAX_DATA * VIOCHAR_NUM_BUF;
841         }
842
843         /*
844          * We retain the spinlock because we want to get an accurate
845          * count and it can change on us between each operation if we
846          * don't hold the spinlock.
847          */
848         for (i = 0; ((i < VIOCHAR_NUM_BUF) && (room < VIOCHAR_MAX_DATA)); i++)
849                 room += (VIOCHAR_MAX_DATA - pi->bufferBytes[i]);
850         spin_unlock_irqrestore(&consolelock, flags);
851
852         if (room > VIOCHAR_MAX_DATA)
853                 room = VIOCHAR_MAX_DATA;
854         return room;
855 }
856
857 /*
858  * TTY chars_in_buffer method
859  */
860 static int viotty_chars_in_buffer(struct tty_struct *tty)
861 {
862         return 0;
863 }
864
865 static int viotty_ioctl(struct tty_struct *tty, struct file *file,
866                         unsigned int cmd, unsigned long arg)
867 {
868         switch (cmd) {
869         /*
870          * the ioctls below read/set the flags usually shown in the leds
871          * don't use them - they will go away without warning
872          */
873         case KDGETLED:
874         case KDGKBLED:
875                 return put_user(0, (char *)arg);
876
877         case KDSKBLED:
878                 return 0;
879         }
880
881         return n_tty_ioctl(tty, file, cmd, arg);
882 }
883
884 /*
885  * Handle an open charLpEvent.  Could be either interrupt or ack
886  */
887 static void vioHandleOpenEvent(struct HvLpEvent *event)
888 {
889         unsigned long flags;
890         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
891         u8 port = cevent->virtual_device;
892         struct port_info *pi;
893         int reject = 0;
894
895         if (event->xFlags.xFunction == HvLpEvent_Function_Ack) {
896                 if (port >= VTTY_PORTS)
897                         return;
898
899                 spin_lock_irqsave(&consolelock, flags);
900                 /* Got the lock, don't cause console output */
901
902                 pi = &port_info[port];
903                 if (event->xRc == HvLpEvent_Rc_Good) {
904                         pi->seq = pi->ack = 0;
905                         /*
906                          * This line allows connections from the primary
907                          * partition but once one is connected from the
908                          * primary partition nothing short of a reboot
909                          * of linux will allow access from the hosting
910                          * partition again without a required iSeries fix.
911                          */
912                         pi->lp = event->xTargetLp;
913                 }
914
915                 spin_unlock_irqrestore(&consolelock, flags);
916                 if (event->xRc != HvLpEvent_Rc_Good)
917                         printk(VIOCONS_KERN_WARN
918                                "handle_open_event: event->xRc == (%d).\n",
919                                event->xRc);
920
921                 if (event->xCorrelationToken != 0) {
922                         atomic_t *aptr= (atomic_t *)event->xCorrelationToken;
923                         atomic_set(aptr, 1);
924                 } else
925                         printk(VIOCONS_KERN_WARN
926                                "wierd...got open ack without atomic\n");
927                 return;
928         }
929
930         /* This had better require an ack, otherwise complain */
931         if (event->xFlags.xAckInd != HvLpEvent_AckInd_DoAck) {
932                 printk(VIOCONS_KERN_WARN "viocharopen without ack bit!\n");
933                 return;
934         }
935
936         spin_lock_irqsave(&consolelock, flags);
937         /* Got the lock, don't cause console output */
938
939         /* Make sure this is a good virtual tty */
940         if (port >= VTTY_PORTS) {
941                 event->xRc = HvLpEvent_Rc_SubtypeError;
942                 cevent->subtype_result_code = viorc_openRejected;
943                 /*
944                  * Flag state here since we can't printk while holding
945                  * a spinlock.
946                  */
947                 reject = 1;
948         } else {
949                 pi = &port_info[port];
950                 if ((pi->lp != HvLpIndexInvalid) &&
951                                 (pi->lp != event->xSourceLp)) {
952                         /*
953                          * If this is tty is already connected to a different
954                          * partition, fail.
955                          */
956                         event->xRc = HvLpEvent_Rc_SubtypeError;
957                         cevent->subtype_result_code = viorc_openRejected;
958                         reject = 2;
959                 } else {
960                         pi->lp = event->xSourceLp;
961                         event->xRc = HvLpEvent_Rc_Good;
962                         cevent->subtype_result_code = viorc_good;
963                         pi->seq = pi->ack = 0;
964                         reject = 0;
965                 }
966         }
967
968         spin_unlock_irqrestore(&consolelock, flags);
969
970         if (reject == 1)
971                 printk(VIOCONS_KERN_WARN "open rejected: bad virtual tty.\n");
972         else if (reject == 2)
973                 printk(VIOCONS_KERN_WARN
974                         "open rejected: console in exclusive use by another partition.\n");
975
976         /* Return the acknowledgement */
977         HvCallEvent_ackLpEvent(event);
978 }
979
980 /*
981  * Handle a close charLpEvent.  This should ONLY be an Interrupt because the
982  * virtual console should never actually issue a close event to the hypervisor
983  * because the virtual console never goes away.  A close event coming from the
984  * hypervisor simply means that there are no client consoles connected to the
985  * virtual console.
986  *
987  * Regardless of the number of connections masqueraded on the other side of
988  * the hypervisor ONLY ONE close event should be called to accompany the ONE
989  * open event that is called.  The close event should ONLY be called when NO
990  * MORE connections (masqueraded or not) exist on the other side of the
991  * hypervisor.
992  */
993 static void vioHandleCloseEvent(struct HvLpEvent *event)
994 {
995         unsigned long flags;
996         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
997         u8 port = cevent->virtual_device;
998
999         if (event->xFlags.xFunction == HvLpEvent_Function_Int) {
1000                 if (port >= VTTY_PORTS) {
1001                         printk(VIOCONS_KERN_WARN
1002                                         "close message from invalid virtual device.\n");
1003                         return;
1004                 }
1005
1006                 /* For closes, just mark the console partition invalid */
1007                 spin_lock_irqsave(&consolelock, flags);
1008                 /* Got the lock, don't cause console output */
1009
1010                 if (port_info[port].lp == event->xSourceLp)
1011                         port_info[port].lp = HvLpIndexInvalid;
1012
1013                 spin_unlock_irqrestore(&consolelock, flags);
1014                 printk(VIOCONS_KERN_INFO "close from %d\n", event->xSourceLp);
1015         } else
1016                 printk(VIOCONS_KERN_WARN
1017                                 "got unexpected close acknowlegement\n");
1018 }
1019
1020 /*
1021  * Handle a config charLpEvent.  Could be either interrupt or ack
1022  */
1023 static void vioHandleConfig(struct HvLpEvent *event)
1024 {
1025         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
1026
1027         HvCall_writeLogBuffer(cevent->data, cevent->len);
1028
1029         if (cevent->data[0] == 0x01)
1030                 printk(VIOCONS_KERN_INFO "window resized to %d: %d: %d: %d\n",
1031                        cevent->data[1], cevent->data[2],
1032                        cevent->data[3], cevent->data[4]);
1033         else
1034                 printk(VIOCONS_KERN_WARN "unknown config event\n");
1035 }
1036
1037 /*
1038  * Handle a data charLpEvent. 
1039  */
1040 static void vioHandleData(struct HvLpEvent *event)
1041 {
1042         struct tty_struct *tty;
1043         unsigned long flags;
1044         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
1045         struct port_info *pi;
1046         int index;
1047         u8 port = cevent->virtual_device;
1048
1049         if (port >= VTTY_PORTS) {
1050                 printk(VIOCONS_KERN_WARN "data on invalid virtual device %d\n",
1051                                 port);
1052                 return;
1053         }
1054
1055         /*
1056          * Hold the spinlock so that we don't take an interrupt that
1057          * changes tty between the time we fetch the port_info
1058          * pointer and the time we paranoia check.
1059          */
1060         spin_lock_irqsave(&consolelock, flags);
1061         pi = &port_info[port];
1062
1063         /*
1064          * Change 05/01/2003 - Ryan Arnold: If a partition other than
1065          * the current exclusive partition tries to send us data
1066          * events then just drop them on the floor because we don't
1067          * want his stinking data.  He isn't authorized to receive
1068          * data because he wasn't the first one to get the console,
1069          * therefore he shouldn't be allowed to send data either.
1070          * This will work without an iSeries fix.
1071          */
1072         if (pi->lp != event->xSourceLp) {
1073                 spin_unlock_irqrestore(&consolelock, flags);
1074                 return;
1075         }
1076
1077         tty = pi->tty;
1078         if (tty == NULL) {
1079                 spin_unlock_irqrestore(&consolelock, flags);
1080                 printk(VIOCONS_KERN_WARN "no tty for virtual device %d\n",
1081                                 port);
1082                 return;
1083         }
1084
1085         if (tty->magic != TTY_MAGIC) {
1086                 spin_unlock_irqrestore(&consolelock, flags);
1087                 printk(VIOCONS_KERN_WARN "tty bad magic\n");
1088                 return;
1089         }
1090
1091         /*
1092          * Just to be paranoid, make sure the tty points back to this port
1093          */
1094         pi = (struct port_info *)tty->driver_data;
1095         if (!pi || viotty_paranoia_check(pi, tty->name, "vioHandleData")) {
1096                 spin_unlock_irqrestore(&consolelock, flags);
1097                 return;
1098         }
1099         spin_unlock_irqrestore(&consolelock, flags);
1100
1101         /*
1102          * Change 07/21/2003 - Ryan Arnold: functionality added to
1103          * support sysrq utilizing ^O as the sysrq key.  The sysrq
1104          * functionality will only work if built into the kernel and
1105          * then only if sysrq is enabled through the proc filesystem.
1106          */
1107         for (index = 0; index < cevent->len; index++) {
1108 #ifdef CONFIG_MAGIC_SYSRQ
1109                 if (sysrq_enabled) {
1110                         /* 0x0f is the ascii character for ^O */
1111                         if (cevent->data[index] == '\x0f') {
1112                                 vio_sysrq_pressed = 1;
1113                                 /*
1114                                  * continue because we don't want to add
1115                                  * the sysrq key into the data string.
1116                                  */
1117                                 continue;
1118                         } else if (vio_sysrq_pressed) {
1119                                 handle_sysrq(cevent->data[index], NULL, tty);
1120                                 vio_sysrq_pressed = 0;
1121                                 /*
1122                                  * continue because we don't want to add
1123                                  * the sysrq sequence into the data string.
1124                                  */
1125                                 continue;
1126                         }
1127                 }
1128 #endif
1129                 /*
1130                  * The sysrq sequence isn't included in this check if
1131                  * sysrq is enabled and compiled into the kernel because
1132                  * the sequence will never get inserted into the buffer.
1133                  * Don't attempt to copy more data into the buffer than we
1134                  * have room for because it would fail without indication.
1135                  */
1136                 if ((tty->flip.count + 1) > TTY_FLIPBUF_SIZE) {
1137                         printk(VIOCONS_KERN_WARN "input buffer overflow!\n");
1138                         break;
1139                 }
1140                 tty_insert_flip_char(tty, cevent->data[index], TTY_NORMAL);
1141         }
1142
1143         /* if cevent->len == 0 then no data was added to the buffer and flip.count == 0 */
1144         if (tty->flip.count)
1145                 /* The next call resets flip.count when the data is flushed. */
1146                 tty_flip_buffer_push(tty);
1147 }
1148
1149 /*
1150  * Handle an ack charLpEvent. 
1151  */
1152 static void vioHandleAck(struct HvLpEvent *event)
1153 {
1154         struct viocharlpevent *cevent = (struct viocharlpevent *)event;
1155         unsigned long flags;
1156         u8 port = cevent->virtual_device;
1157
1158         if (port >= VTTY_PORTS) {
1159                 printk(VIOCONS_KERN_WARN "data on invalid virtual device\n");
1160                 return;
1161         }
1162
1163         spin_lock_irqsave(&consolelock, flags);
1164         port_info[port].ack = event->xCorrelationToken;
1165         spin_unlock_irqrestore(&consolelock, flags);
1166
1167         if (port_info[port].used)
1168                 send_buffers(&port_info[port]);
1169 }
1170
1171 /*
1172  * Handle charLpEvents and route to the appropriate routine
1173  */
1174 static void vioHandleCharEvent(struct HvLpEvent *event)
1175 {
1176         int charminor;
1177
1178         if (event == NULL)
1179                 return;
1180
1181         charminor = event->xSubtype & VIOMINOR_SUBTYPE_MASK;
1182         switch (charminor) {
1183         case viocharopen:
1184                 vioHandleOpenEvent(event);
1185                 break;
1186         case viocharclose:
1187                 vioHandleCloseEvent(event);
1188                 break;
1189         case viochardata:
1190                 vioHandleData(event);
1191                 break;
1192         case viocharack:
1193                 vioHandleAck(event);
1194                 break;
1195         case viocharconfig:
1196                 vioHandleConfig(event);
1197                 break;
1198         default:
1199                 if ((event->xFlags.xFunction == HvLpEvent_Function_Int) &&
1200                     (event->xFlags.xAckInd == HvLpEvent_AckInd_DoAck)) {
1201                         event->xRc = HvLpEvent_Rc_InvalidSubtype;
1202                         HvCallEvent_ackLpEvent(event);
1203                 }
1204         }
1205 }
1206
1207 /*
1208  * Send an open event
1209  */
1210 static int send_open(HvLpIndex remoteLp, void *sem)
1211 {
1212         return HvCallEvent_signalLpEventFast(remoteLp,
1213                         HvLpEvent_Type_VirtualIo,
1214                         viomajorsubtype_chario | viocharopen,
1215                         HvLpEvent_AckInd_DoAck, HvLpEvent_AckType_ImmediateAck,
1216                         viopath_sourceinst(remoteLp),
1217                         viopath_targetinst(remoteLp),
1218                         (u64)(unsigned long)sem, VIOVERSION << 16,
1219                         0, 0, 0, 0);
1220 }
1221
1222 static struct tty_operations serial_ops = {
1223         .open = viotty_open,
1224         .close = viotty_close,
1225         .write = viotty_write,
1226         .put_char = viotty_put_char,
1227         .write_room = viotty_write_room,
1228         .chars_in_buffer = viotty_chars_in_buffer,
1229         .ioctl = viotty_ioctl,
1230 };
1231
1232 static int __init viocons_init2(void)
1233 {
1234         atomic_t wait_flag;
1235         int rc;
1236
1237         /* +2 for fudge */
1238         rc = viopath_open(HvLpConfig_getPrimaryLpIndex(),
1239                         viomajorsubtype_chario, VIOCHAR_WINDOW + 2);
1240         if (rc)
1241                 printk(VIOCONS_KERN_WARN "error opening to primary %d\n", rc);
1242
1243         if (viopath_hostLp == HvLpIndexInvalid)
1244                 vio_set_hostlp();
1245
1246         /*
1247          * And if the primary is not the same as the hosting LP, open to the 
1248          * hosting lp
1249          */
1250         if ((viopath_hostLp != HvLpIndexInvalid) &&
1251             (viopath_hostLp != HvLpConfig_getPrimaryLpIndex())) {
1252                 printk(VIOCONS_KERN_INFO "open path to hosting (%d)\n",
1253                                 viopath_hostLp);
1254                 rc = viopath_open(viopath_hostLp, viomajorsubtype_chario,
1255                                 VIOCHAR_WINDOW + 2);    /* +2 for fudge */
1256                 if (rc)
1257                         printk(VIOCONS_KERN_WARN
1258                                 "error opening to partition %d: %d\n",
1259                                 viopath_hostLp, rc);
1260         }
1261
1262         if (vio_setHandler(viomajorsubtype_chario, vioHandleCharEvent) < 0)
1263                 printk(VIOCONS_KERN_WARN
1264                                 "error seting handler for console events!\n");
1265
1266         /*
1267          * First, try to open the console to the hosting lp.
1268          * Wait on a semaphore for the response.
1269          */
1270         atomic_set(&wait_flag, 0);
1271         if ((viopath_isactive(viopath_hostLp)) &&
1272             (send_open(viopath_hostLp, (void *)&wait_flag) == 0)) {
1273                 printk(VIOCONS_KERN_INFO "hosting partition %d\n",
1274                         viopath_hostLp);
1275                 while (atomic_read(&wait_flag) == 0)
1276                         mb();
1277                 atomic_set(&wait_flag, 0);
1278         }
1279
1280         /*
1281          * If we don't have an active console, try the primary
1282          */
1283         if ((!viopath_isactive(port_info[0].lp)) &&
1284             (viopath_isactive(HvLpConfig_getPrimaryLpIndex())) &&
1285             (send_open(HvLpConfig_getPrimaryLpIndex(), (void *)&wait_flag)
1286              == 0)) {
1287                 printk(VIOCONS_KERN_INFO "opening console to primary partition\n");
1288                 while (atomic_read(&wait_flag) == 0)
1289                         mb();
1290         }
1291
1292         /* Initialize the tty_driver structure */
1293         viotty_driver = alloc_tty_driver(VTTY_PORTS);
1294         viotty_driver->owner = THIS_MODULE;
1295         viotty_driver->driver_name = "vioconsole";
1296         viotty_driver->devfs_name = "vcs/";
1297         viotty_driver->name = "tty";
1298         viotty_driver->name_base = 1;
1299         viotty_driver->major = TTY_MAJOR;
1300         viotty_driver->minor_start = 1;
1301         viotty_driver->type = TTY_DRIVER_TYPE_CONSOLE;
1302         viotty_driver->subtype = 1;
1303         viotty_driver->init_termios = tty_std_termios;
1304         viotty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_RESET_TERMIOS;
1305         tty_set_operations(viotty_driver, &serial_ops);
1306
1307         if (tty_register_driver(viotty_driver)) {
1308                 printk(VIOCONS_KERN_WARN "couldn't register console driver\n");
1309                 put_tty_driver(viotty_driver);
1310                 viotty_driver = NULL;
1311         }
1312
1313         viocons_init_cfu_buffer();
1314
1315         unregister_console(&viocons_early);
1316         register_console(&viocons);
1317
1318         return 0;
1319 }
1320
1321 static int __init viocons_init(void)
1322 {
1323         int i;
1324
1325         printk(VIOCONS_KERN_INFO "registering console\n");
1326         for (i = 0; i < VTTY_PORTS; i++) {
1327                 port_info[i].lp = HvLpIndexInvalid;
1328                 port_info[i].magic = VIOTTY_MAGIC;
1329         }
1330         HvCall_setLogBufferFormatAndCodepage(HvCall_LogBuffer_ASCII, 437);
1331         register_console(&viocons_early);
1332         return 0;
1333 }
1334
1335 console_initcall(viocons_init);
1336 module_init(viocons_init2);