Merge branch 'for-np' of git://git.wormnet.eu/alex/ts78xx into orion/master
[linux-2.6] / drivers / char / hvc_iucv.c
1 /*
2  * hvc_iucv.c - z/VM IUCV hypervisor console (HVC) device driver
3  *
4  * This HVC device driver provides terminal access using
5  * z/VM IUCV communication paths.
6  *
7  * Copyright IBM Corp. 2008
8  *
9  * Author(s):   Hendrik Brueckner <brueckner@linux.vnet.ibm.com>
10  */
11 #define KMSG_COMPONENT          "hvc_iucv"
12 #define pr_fmt(fmt)             KMSG_COMPONENT ": " fmt
13
14 #include <linux/types.h>
15 #include <asm/ebcdic.h>
16 #include <linux/delay.h>
17 #include <linux/init.h>
18 #include <linux/mempool.h>
19 #include <linux/module.h>
20 #include <linux/tty.h>
21 #include <linux/wait.h>
22 #include <net/iucv/iucv.h>
23
24 #include "hvc_console.h"
25
26
27 /* General device driver settings */
28 #define HVC_IUCV_MAGIC          0xc9e4c3e5
29 #define MAX_HVC_IUCV_LINES      HVC_ALLOC_TTY_ADAPTERS
30 #define MEMPOOL_MIN_NR          (PAGE_SIZE / sizeof(struct iucv_tty_buffer)/4)
31
32 /* IUCV TTY message  */
33 #define MSG_VERSION             0x02    /* Message version */
34 #define MSG_TYPE_ERROR          0x01    /* Error message */
35 #define MSG_TYPE_TERMENV        0x02    /* Terminal environment variable */
36 #define MSG_TYPE_TERMIOS        0x04    /* Terminal IO struct update */
37 #define MSG_TYPE_WINSIZE        0x08    /* Terminal window size update */
38 #define MSG_TYPE_DATA           0x10    /* Terminal data */
39
40 struct iucv_tty_msg {
41         u8      version;                /* Message version */
42         u8      type;                   /* Message type */
43 #define MSG_MAX_DATALEN         ((u16)(~0))
44         u16     datalen;                /* Payload length */
45         u8      data[];                 /* Payload buffer */
46 } __attribute__((packed));
47 #define MSG_SIZE(s)             ((s) + offsetof(struct iucv_tty_msg, data))
48
49 enum iucv_state_t {
50         IUCV_DISCONN    = 0,
51         IUCV_CONNECTED  = 1,
52         IUCV_SEVERED    = 2,
53 };
54
55 enum tty_state_t {
56         TTY_CLOSED      = 0,
57         TTY_OPENED      = 1,
58 };
59
60 struct hvc_iucv_private {
61         struct hvc_struct       *hvc;           /* HVC struct reference */
62         u8                      srv_name[8];    /* IUCV service name (ebcdic) */
63         unsigned char           is_console;     /* Linux console usage flag */
64         enum iucv_state_t       iucv_state;     /* IUCV connection status */
65         enum tty_state_t        tty_state;      /* TTY status */
66         struct iucv_path        *path;          /* IUCV path pointer */
67         spinlock_t              lock;           /* hvc_iucv_private lock */
68 #define SNDBUF_SIZE             (PAGE_SIZE)     /* must be < MSG_MAX_DATALEN */
69         void                    *sndbuf;        /* send buffer            */
70         size_t                  sndbuf_len;     /* length of send buffer  */
71 #define QUEUE_SNDBUF_DELAY      (HZ / 25)
72         struct delayed_work     sndbuf_work;    /* work: send iucv msg(s) */
73         wait_queue_head_t       sndbuf_waitq;   /* wait for send completion */
74         struct list_head        tty_outqueue;   /* outgoing IUCV messages */
75         struct list_head        tty_inqueue;    /* incoming IUCV messages */
76 };
77
78 struct iucv_tty_buffer {
79         struct list_head        list;   /* list pointer */
80         struct iucv_message     msg;    /* store an IUCV message */
81         size_t                  offset; /* data buffer offset */
82         struct iucv_tty_msg     *mbuf;  /* buffer to store input/output data */
83 };
84
85 /* IUCV callback handler */
86 static  int hvc_iucv_path_pending(struct iucv_path *, u8[8], u8[16]);
87 static void hvc_iucv_path_severed(struct iucv_path *, u8[16]);
88 static void hvc_iucv_msg_pending(struct iucv_path *, struct iucv_message *);
89 static void hvc_iucv_msg_complete(struct iucv_path *, struct iucv_message *);
90
91
92 /* Kernel module parameter: use one terminal device as default */
93 static unsigned long hvc_iucv_devices = 1;
94
95 /* Array of allocated hvc iucv tty lines... */
96 static struct hvc_iucv_private *hvc_iucv_table[MAX_HVC_IUCV_LINES];
97 #define IUCV_HVC_CON_IDX        (0)
98
99 /* Kmem cache and mempool for iucv_tty_buffer elements */
100 static struct kmem_cache *hvc_iucv_buffer_cache;
101 static mempool_t *hvc_iucv_mempool;
102
103 /* IUCV handler callback functions */
104 static struct iucv_handler hvc_iucv_handler = {
105         .path_pending  = hvc_iucv_path_pending,
106         .path_severed  = hvc_iucv_path_severed,
107         .message_complete = hvc_iucv_msg_complete,
108         .message_pending  = hvc_iucv_msg_pending,
109 };
110
111
112 /**
113  * hvc_iucv_get_private() - Return a struct hvc_iucv_private instance.
114  * @num:        The HVC virtual terminal number (vtermno)
115  *
116  * This function returns the struct hvc_iucv_private instance that corresponds
117  * to the HVC virtual terminal number specified as parameter @num.
118  */
119 struct hvc_iucv_private *hvc_iucv_get_private(uint32_t num)
120 {
121         if ((num < HVC_IUCV_MAGIC) || (num - HVC_IUCV_MAGIC > hvc_iucv_devices))
122                 return NULL;
123         return hvc_iucv_table[num - HVC_IUCV_MAGIC];
124 }
125
126 /**
127  * alloc_tty_buffer() - Return a new struct iucv_tty_buffer element.
128  * @size:       Size of the internal buffer used to store data.
129  * @flags:      Memory allocation flags passed to mempool.
130  *
131  * This function allocates a new struct iucv_tty_buffer element and, optionally,
132  * allocates an internal data buffer with the specified size @size.
133  * Note: The total message size arises from the internal buffer size and the
134  *       members of the iucv_tty_msg structure.
135  * The function returns NULL if memory allocation has failed.
136  */
137 static struct iucv_tty_buffer *alloc_tty_buffer(size_t size, gfp_t flags)
138 {
139         struct iucv_tty_buffer *bufp;
140
141         bufp = mempool_alloc(hvc_iucv_mempool, flags);
142         if (!bufp)
143                 return NULL;
144         memset(bufp, 0, sizeof(*bufp));
145
146         if (size > 0) {
147                 bufp->msg.length = MSG_SIZE(size);
148                 bufp->mbuf = kmalloc(bufp->msg.length, flags);
149                 if (!bufp->mbuf) {
150                         mempool_free(bufp, hvc_iucv_mempool);
151                         return NULL;
152                 }
153                 bufp->mbuf->version = MSG_VERSION;
154                 bufp->mbuf->type    = MSG_TYPE_DATA;
155                 bufp->mbuf->datalen = (u16) size;
156         }
157         return bufp;
158 }
159
160 /**
161  * destroy_tty_buffer() - destroy struct iucv_tty_buffer element.
162  * @bufp:       Pointer to a struct iucv_tty_buffer element, SHALL NOT be NULL.
163  */
164 static void destroy_tty_buffer(struct iucv_tty_buffer *bufp)
165 {
166         kfree(bufp->mbuf);
167         mempool_free(bufp, hvc_iucv_mempool);
168 }
169
170 /**
171  * destroy_tty_buffer_list() - call destroy_tty_buffer() for each list element.
172  * @list:       List containing struct iucv_tty_buffer elements.
173  */
174 static void destroy_tty_buffer_list(struct list_head *list)
175 {
176         struct iucv_tty_buffer *ent, *next;
177
178         list_for_each_entry_safe(ent, next, list, list) {
179                 list_del(&ent->list);
180                 destroy_tty_buffer(ent);
181         }
182 }
183
184 /**
185  * hvc_iucv_write() - Receive IUCV message & write data to HVC buffer.
186  * @priv:               Pointer to struct hvc_iucv_private
187  * @buf:                HVC buffer for writing received terminal data.
188  * @count:              HVC buffer size.
189  * @has_more_data:      Pointer to an int variable.
190  *
191  * The function picks up pending messages from the input queue and receives
192  * the message data that is then written to the specified buffer @buf.
193  * If the buffer size @count is less than the data message size, the
194  * message is kept on the input queue and @has_more_data is set to 1.
195  * If all message data has been written, the message is removed from
196  * the input queue.
197  *
198  * The function returns the number of bytes written to the terminal, zero if
199  * there are no pending data messages available or if there is no established
200  * IUCV path.
201  * If the IUCV path has been severed, then -EPIPE is returned to cause a
202  * hang up (that is issued by the HVC layer).
203  */
204 static int hvc_iucv_write(struct hvc_iucv_private *priv,
205                           char *buf, int count, int *has_more_data)
206 {
207         struct iucv_tty_buffer *rb;
208         int written;
209         int rc;
210
211         /* immediately return if there is no IUCV connection */
212         if (priv->iucv_state == IUCV_DISCONN)
213                 return 0;
214
215         /* if the IUCV path has been severed, return -EPIPE to inform the
216          * HVC layer to hang up the tty device. */
217         if (priv->iucv_state == IUCV_SEVERED)
218                 return -EPIPE;
219
220         /* check if there are pending messages */
221         if (list_empty(&priv->tty_inqueue))
222                 return 0;
223
224         /* receive an iucv message and flip data to the tty (ldisc) */
225         rb = list_first_entry(&priv->tty_inqueue, struct iucv_tty_buffer, list);
226
227         written = 0;
228         if (!rb->mbuf) { /* message not yet received ... */
229                 /* allocate mem to store msg data; if no memory is available
230                  * then leave the buffer on the list and re-try later */
231                 rb->mbuf = kmalloc(rb->msg.length, GFP_ATOMIC);
232                 if (!rb->mbuf)
233                         return -ENOMEM;
234
235                 rc = __iucv_message_receive(priv->path, &rb->msg, 0,
236                                             rb->mbuf, rb->msg.length, NULL);
237                 switch (rc) {
238                 case 0: /* Successful       */
239                         break;
240                 case 2: /* No message found */
241                 case 9: /* Message purged   */
242                         break;
243                 default:
244                         written = -EIO;
245                 }
246                 /* remove buffer if an error has occured or received data
247                  * is not correct */
248                 if (rc || (rb->mbuf->version != MSG_VERSION) ||
249                           (rb->msg.length    != MSG_SIZE(rb->mbuf->datalen)))
250                         goto out_remove_buffer;
251         }
252
253         switch (rb->mbuf->type) {
254         case MSG_TYPE_DATA:
255                 written = min_t(int, rb->mbuf->datalen - rb->offset, count);
256                 memcpy(buf, rb->mbuf->data + rb->offset, written);
257                 if (written < (rb->mbuf->datalen - rb->offset)) {
258                         rb->offset += written;
259                         *has_more_data = 1;
260                         goto out_written;
261                 }
262                 break;
263
264         case MSG_TYPE_WINSIZE:
265                 if (rb->mbuf->datalen != sizeof(struct winsize))
266                         break;
267                 hvc_resize(priv->hvc, *((struct winsize *) rb->mbuf->data));
268                 break;
269
270         case MSG_TYPE_ERROR:    /* ignored ... */
271         case MSG_TYPE_TERMENV:  /* ignored ... */
272         case MSG_TYPE_TERMIOS:  /* ignored ... */
273                 break;
274         }
275
276 out_remove_buffer:
277         list_del(&rb->list);
278         destroy_tty_buffer(rb);
279         *has_more_data = !list_empty(&priv->tty_inqueue);
280
281 out_written:
282         return written;
283 }
284
285 /**
286  * hvc_iucv_get_chars() - HVC get_chars operation.
287  * @vtermno:    HVC virtual terminal number.
288  * @buf:        Pointer to a buffer to store data
289  * @count:      Size of buffer available for writing
290  *
291  * The HVC thread calls this method to read characters from the back-end.
292  * If an IUCV communication path has been established, pending IUCV messages
293  * are received and data is copied into buffer @buf up to @count bytes.
294  *
295  * Locking:     The routine gets called under an irqsave() spinlock; and
296  *              the routine locks the struct hvc_iucv_private->lock to call
297  *              helper functions.
298  */
299 static int hvc_iucv_get_chars(uint32_t vtermno, char *buf, int count)
300 {
301         struct hvc_iucv_private *priv = hvc_iucv_get_private(vtermno);
302         int written;
303         int has_more_data;
304
305         if (count <= 0)
306                 return 0;
307
308         if (!priv)
309                 return -ENODEV;
310
311         spin_lock(&priv->lock);
312         has_more_data = 0;
313         written = hvc_iucv_write(priv, buf, count, &has_more_data);
314         spin_unlock(&priv->lock);
315
316         /* if there are still messages on the queue... schedule another run */
317         if (has_more_data)
318                 hvc_kick();
319
320         return written;
321 }
322
323 /**
324  * hvc_iucv_queue() - Buffer terminal data for sending.
325  * @priv:       Pointer to struct hvc_iucv_private instance.
326  * @buf:        Buffer containing data to send.
327  * @count:      Size of buffer and amount of data to send.
328  *
329  * The function queues data for sending. To actually send the buffered data,
330  * a work queue function is scheduled (with QUEUE_SNDBUF_DELAY).
331  * The function returns the number of data bytes that has been buffered.
332  *
333  * If the device is not connected, data is ignored and the function returns
334  * @count.
335  * If the buffer is full, the function returns 0.
336  * If an existing IUCV communicaton path has been severed, -EPIPE is returned
337  * (that can be passed to HVC layer to cause a tty hangup).
338  */
339 static int hvc_iucv_queue(struct hvc_iucv_private *priv, const char *buf,
340                           int count)
341 {
342         size_t len;
343
344         if (priv->iucv_state == IUCV_DISCONN)
345                 return count;                   /* ignore data */
346
347         if (priv->iucv_state == IUCV_SEVERED)
348                 return -EPIPE;
349
350         len = min_t(size_t, count, SNDBUF_SIZE - priv->sndbuf_len);
351         if (!len)
352                 return 0;
353
354         memcpy(priv->sndbuf + priv->sndbuf_len, buf, len);
355         priv->sndbuf_len += len;
356
357         if (priv->iucv_state == IUCV_CONNECTED)
358                 schedule_delayed_work(&priv->sndbuf_work, QUEUE_SNDBUF_DELAY);
359
360         return len;
361 }
362
363 /**
364  * hvc_iucv_send() - Send an IUCV message containing terminal data.
365  * @priv:       Pointer to struct hvc_iucv_private instance.
366  *
367  * If an IUCV communication path has been established, the buffered output data
368  * is sent via an IUCV message and the number of bytes sent is returned.
369  * Returns 0 if there is no established IUCV communication path or
370  * -EPIPE if an existing IUCV communicaton path has been severed.
371  */
372 static int hvc_iucv_send(struct hvc_iucv_private *priv)
373 {
374         struct iucv_tty_buffer *sb;
375         int rc, len;
376
377         if (priv->iucv_state == IUCV_SEVERED)
378                 return -EPIPE;
379
380         if (priv->iucv_state == IUCV_DISCONN)
381                 return -EIO;
382
383         if (!priv->sndbuf_len)
384                 return 0;
385
386         /* allocate internal buffer to store msg data and also compute total
387          * message length */
388         sb = alloc_tty_buffer(priv->sndbuf_len, GFP_ATOMIC);
389         if (!sb)
390                 return -ENOMEM;
391
392         memcpy(sb->mbuf->data, priv->sndbuf, priv->sndbuf_len);
393         sb->mbuf->datalen = (u16) priv->sndbuf_len;
394         sb->msg.length = MSG_SIZE(sb->mbuf->datalen);
395
396         list_add_tail(&sb->list, &priv->tty_outqueue);
397
398         rc = __iucv_message_send(priv->path, &sb->msg, 0, 0,
399                                  (void *) sb->mbuf, sb->msg.length);
400         if (rc) {
401                 /* drop the message here; however we might want to handle
402                  * 0x03 (msg limit reached) by trying again... */
403                 list_del(&sb->list);
404                 destroy_tty_buffer(sb);
405         }
406         len = priv->sndbuf_len;
407         priv->sndbuf_len = 0;
408
409         return len;
410 }
411
412 /**
413  * hvc_iucv_sndbuf_work() - Send buffered data over IUCV
414  * @work:       Work structure.
415  *
416  * This work queue function sends buffered output data over IUCV and,
417  * if not all buffered data could be sent, reschedules itself.
418  */
419 static void hvc_iucv_sndbuf_work(struct work_struct *work)
420 {
421         struct hvc_iucv_private *priv;
422
423         priv = container_of(work, struct hvc_iucv_private, sndbuf_work.work);
424         if (!priv)
425                 return;
426
427         spin_lock_bh(&priv->lock);
428         hvc_iucv_send(priv);
429         spin_unlock_bh(&priv->lock);
430 }
431
432 /**
433  * hvc_iucv_put_chars() - HVC put_chars operation.
434  * @vtermno:    HVC virtual terminal number.
435  * @buf:        Pointer to an buffer to read data from
436  * @count:      Size of buffer available for reading
437  *
438  * The HVC thread calls this method to write characters to the back-end.
439  * The function calls hvc_iucv_queue() to queue terminal data for sending.
440  *
441  * Locking:     The method gets called under an irqsave() spinlock; and
442  *              locks struct hvc_iucv_private->lock.
443  */
444 static int hvc_iucv_put_chars(uint32_t vtermno, const char *buf, int count)
445 {
446         struct hvc_iucv_private *priv = hvc_iucv_get_private(vtermno);
447         int queued;
448
449         if (count <= 0)
450                 return 0;
451
452         if (!priv)
453                 return -ENODEV;
454
455         spin_lock(&priv->lock);
456         queued = hvc_iucv_queue(priv, buf, count);
457         spin_unlock(&priv->lock);
458
459         return queued;
460 }
461
462 /**
463  * hvc_iucv_notifier_add() - HVC notifier for opening a TTY for the first time.
464  * @hp: Pointer to the HVC device (struct hvc_struct)
465  * @id: Additional data (originally passed to hvc_alloc): the index of an struct
466  *      hvc_iucv_private instance.
467  *
468  * The function sets the tty state to TTY_OPENED for the struct hvc_iucv_private
469  * instance that is derived from @id. Always returns 0.
470  *
471  * Locking:     struct hvc_iucv_private->lock, spin_lock_bh
472  */
473 static int hvc_iucv_notifier_add(struct hvc_struct *hp, int id)
474 {
475         struct hvc_iucv_private *priv;
476
477         priv = hvc_iucv_get_private(id);
478         if (!priv)
479                 return 0;
480
481         spin_lock_bh(&priv->lock);
482         priv->tty_state = TTY_OPENED;
483         spin_unlock_bh(&priv->lock);
484
485         return 0;
486 }
487
488 /**
489  * hvc_iucv_cleanup() - Clean up and reset a z/VM IUCV HVC instance.
490  * @priv:       Pointer to the struct hvc_iucv_private instance.
491  */
492 static void hvc_iucv_cleanup(struct hvc_iucv_private *priv)
493 {
494         destroy_tty_buffer_list(&priv->tty_outqueue);
495         destroy_tty_buffer_list(&priv->tty_inqueue);
496
497         priv->tty_state = TTY_CLOSED;
498         priv->iucv_state = IUCV_DISCONN;
499
500         priv->sndbuf_len = 0;
501 }
502
503 /**
504  * tty_outqueue_empty() - Test if the tty outq is empty
505  * @priv:       Pointer to struct hvc_iucv_private instance.
506  */
507 static inline int tty_outqueue_empty(struct hvc_iucv_private *priv)
508 {
509         int rc;
510
511         spin_lock_bh(&priv->lock);
512         rc = list_empty(&priv->tty_outqueue);
513         spin_unlock_bh(&priv->lock);
514
515         return rc;
516 }
517
518 /**
519  * flush_sndbuf_sync() - Flush send buffer and wait for completion
520  * @priv:       Pointer to struct hvc_iucv_private instance.
521  *
522  * The routine cancels a pending sndbuf work, calls hvc_iucv_send()
523  * to flush any buffered terminal output data and waits for completion.
524  */
525 static void flush_sndbuf_sync(struct hvc_iucv_private *priv)
526 {
527         int sync_wait;
528
529         cancel_delayed_work_sync(&priv->sndbuf_work);
530
531         spin_lock_bh(&priv->lock);
532         hvc_iucv_send(priv);            /* force sending buffered data */
533         sync_wait = !list_empty(&priv->tty_outqueue); /* anything queued ? */
534         spin_unlock_bh(&priv->lock);
535
536         if (sync_wait)
537                 wait_event_timeout(priv->sndbuf_waitq,
538                                    tty_outqueue_empty(priv), HZ);
539 }
540
541 /**
542  * hvc_iucv_notifier_hangup() - HVC notifier for TTY hangups.
543  * @hp:         Pointer to the HVC device (struct hvc_struct)
544  * @id:         Additional data (originally passed to hvc_alloc):
545  *              the index of an struct hvc_iucv_private instance.
546  *
547  * This routine notifies the HVC back-end that a tty hangup (carrier loss,
548  * virtual or otherwise) has occured.
549  * The z/VM IUCV HVC device driver ignores virtual hangups (vhangup())
550  * to keep an existing IUCV communication path established.
551  * (Background: vhangup() is called from user space (by getty or login) to
552  *              disable writing to the tty by other applications).
553  * If the tty has been opened and an established IUCV path has been severed
554  * (we caused the tty hangup), the function calls hvc_iucv_cleanup().
555  *
556  * Locking:     struct hvc_iucv_private->lock
557  */
558 static void hvc_iucv_notifier_hangup(struct hvc_struct *hp, int id)
559 {
560         struct hvc_iucv_private *priv;
561
562         priv = hvc_iucv_get_private(id);
563         if (!priv)
564                 return;
565
566         flush_sndbuf_sync(priv);
567
568         spin_lock_bh(&priv->lock);
569         /* NOTE: If the hangup was scheduled by ourself (from the iucv
570          *       path_servered callback [IUCV_SEVERED]), we have to clean up
571          *       our structure and to set state to TTY_CLOSED.
572          *       If the tty was hung up otherwise (e.g. vhangup()), then we
573          *       ignore this hangup and keep an established IUCV path open...
574          *       (...the reason is that we are not able to connect back to the
575          *       client if we disconnect on hang up) */
576         priv->tty_state = TTY_CLOSED;
577
578         if (priv->iucv_state == IUCV_SEVERED)
579                 hvc_iucv_cleanup(priv);
580         spin_unlock_bh(&priv->lock);
581 }
582
583 /**
584  * hvc_iucv_notifier_del() - HVC notifier for closing a TTY for the last time.
585  * @hp:         Pointer to the HVC device (struct hvc_struct)
586  * @id:         Additional data (originally passed to hvc_alloc):
587  *              the index of an struct hvc_iucv_private instance.
588  *
589  * This routine notifies the HVC back-end that the last tty device fd has been
590  * closed.  The function calls hvc_iucv_cleanup() to clean up the struct
591  * hvc_iucv_private instance.
592  *
593  * Locking:     struct hvc_iucv_private->lock
594  */
595 static void hvc_iucv_notifier_del(struct hvc_struct *hp, int id)
596 {
597         struct hvc_iucv_private *priv;
598         struct iucv_path        *path;
599
600         priv = hvc_iucv_get_private(id);
601         if (!priv)
602                 return;
603
604         flush_sndbuf_sync(priv);
605
606         spin_lock_bh(&priv->lock);
607         path = priv->path;              /* save reference to IUCV path */
608         priv->path = NULL;
609         hvc_iucv_cleanup(priv);
610         spin_unlock_bh(&priv->lock);
611
612         /* sever IUCV path outside of priv->lock due to lock ordering of:
613          * priv->lock <--> iucv_table_lock */
614         if (path) {
615                 iucv_path_sever(path, NULL);
616                 iucv_path_free(path);
617         }
618 }
619
620 /**
621  * hvc_iucv_path_pending() - IUCV handler to process a connection request.
622  * @path:       Pending path (struct iucv_path)
623  * @ipvmid:     z/VM system identifier of originator
624  * @ipuser:     User specified data for this path
625  *              (AF_IUCV: port/service name and originator port)
626  *
627  * The function uses the @ipuser data to determine if the pending path belongs
628  * to a terminal managed by this device driver.
629  * If the path belongs to this driver, ensure that the terminal is not accessed
630  * multiple times (only one connection to a terminal is allowed).
631  * If the terminal is not yet connected, the pending path is accepted and is
632  * associated to the appropriate struct hvc_iucv_private instance.
633  *
634  * Returns 0 if @path belongs to a terminal managed by the this device driver;
635  * otherwise returns -ENODEV in order to dispatch this path to other handlers.
636  *
637  * Locking:     struct hvc_iucv_private->lock
638  */
639 static  int hvc_iucv_path_pending(struct iucv_path *path,
640                                   u8 ipvmid[8], u8 ipuser[16])
641 {
642         struct hvc_iucv_private *priv;
643         u8 nuser_data[16];
644         int i, rc;
645
646         priv = NULL;
647         for (i = 0; i < hvc_iucv_devices; i++)
648                 if (hvc_iucv_table[i] &&
649                     (0 == memcmp(hvc_iucv_table[i]->srv_name, ipuser, 8))) {
650                         priv = hvc_iucv_table[i];
651                         break;
652                 }
653         if (!priv)
654                 return -ENODEV;
655
656         spin_lock(&priv->lock);
657
658         /* If the terminal is already connected or being severed, then sever
659          * this path to enforce that there is only ONE established communication
660          * path per terminal. */
661         if (priv->iucv_state != IUCV_DISCONN) {
662                 iucv_path_sever(path, ipuser);
663                 iucv_path_free(path);
664                 goto out_path_handled;
665         }
666
667         /* accept path */
668         memcpy(nuser_data, ipuser + 8, 8);  /* remote service (for af_iucv) */
669         memcpy(nuser_data + 8, ipuser, 8);  /* local service  (for af_iucv) */
670         path->msglim = 0xffff;              /* IUCV MSGLIMIT */
671         path->flags &= ~IUCV_IPRMDATA;      /* TODO: use IUCV_IPRMDATA */
672         rc = iucv_path_accept(path, &hvc_iucv_handler, nuser_data, priv);
673         if (rc) {
674                 iucv_path_sever(path, ipuser);
675                 iucv_path_free(path);
676                 goto out_path_handled;
677         }
678         priv->path = path;
679         priv->iucv_state = IUCV_CONNECTED;
680
681         /* flush buffered output data... */
682         schedule_delayed_work(&priv->sndbuf_work, 5);
683
684 out_path_handled:
685         spin_unlock(&priv->lock);
686         return 0;
687 }
688
689 /**
690  * hvc_iucv_path_severed() - IUCV handler to process a path sever.
691  * @path:       Pending path (struct iucv_path)
692  * @ipuser:     User specified data for this path
693  *              (AF_IUCV: port/service name and originator port)
694  *
695  * The function also severs the path (as required by the IUCV protocol) and
696  * sets the iucv state to IUCV_SEVERED for the associated struct
697  * hvc_iucv_private instance. Later, the IUCV_SEVERED state triggers a tty
698  * hangup (hvc_iucv_get_chars() / hvc_iucv_write()).
699  * If tty portion of the HVC is closed, clean up the outqueue.
700  *
701  * Locking:     struct hvc_iucv_private->lock
702  */
703 static void hvc_iucv_path_severed(struct iucv_path *path, u8 ipuser[16])
704 {
705         struct hvc_iucv_private *priv = path->private;
706
707         spin_lock(&priv->lock);
708         priv->iucv_state = IUCV_SEVERED;
709
710         /* If the tty has not yet been opened, clean up the hvc_iucv_private
711          * structure to allow re-connects.
712          * This is also done for our console device because console hangups
713          * are handled specially and no notifier is called by HVC.
714          * The tty session is active (TTY_OPEN) and ready for re-connects...
715          *
716          * If it has been opened, let get_chars() return -EPIPE to signal the
717          * HVC layer to hang up the tty.
718          * If so, we need to wake up the HVC thread to call get_chars()...
719          */
720         priv->path = NULL;
721         if (priv->tty_state == TTY_CLOSED)
722                 hvc_iucv_cleanup(priv);
723         else
724                 if (priv->is_console) {
725                         hvc_iucv_cleanup(priv);
726                         priv->tty_state = TTY_OPENED;
727                 } else
728                         hvc_kick();
729         spin_unlock(&priv->lock);
730
731         /* finally sever path (outside of priv->lock due to lock ordering) */
732         iucv_path_sever(path, ipuser);
733         iucv_path_free(path);
734 }
735
736 /**
737  * hvc_iucv_msg_pending() - IUCV handler to process an incoming IUCV message.
738  * @path:       Pending path (struct iucv_path)
739  * @msg:        Pointer to the IUCV message
740  *
741  * The function puts an incoming message on the input queue for later
742  * processing (by hvc_iucv_get_chars() / hvc_iucv_write()).
743  * If the tty has not yet been opened, the message is rejected.
744  *
745  * Locking:     struct hvc_iucv_private->lock
746  */
747 static void hvc_iucv_msg_pending(struct iucv_path *path,
748                                  struct iucv_message *msg)
749 {
750         struct hvc_iucv_private *priv = path->private;
751         struct iucv_tty_buffer *rb;
752
753         /* reject messages that exceed max size of iucv_tty_msg->datalen */
754         if (msg->length > MSG_SIZE(MSG_MAX_DATALEN)) {
755                 iucv_message_reject(path, msg);
756                 return;
757         }
758
759         spin_lock(&priv->lock);
760
761         /* reject messages if tty has not yet been opened */
762         if (priv->tty_state == TTY_CLOSED) {
763                 iucv_message_reject(path, msg);
764                 goto unlock_return;
765         }
766
767         /* allocate tty buffer to save iucv msg only */
768         rb = alloc_tty_buffer(0, GFP_ATOMIC);
769         if (!rb) {
770                 iucv_message_reject(path, msg);
771                 goto unlock_return;     /* -ENOMEM */
772         }
773         rb->msg = *msg;
774
775         list_add_tail(&rb->list, &priv->tty_inqueue);
776
777         hvc_kick();     /* wake up hvc thread */
778
779 unlock_return:
780         spin_unlock(&priv->lock);
781 }
782
783 /**
784  * hvc_iucv_msg_complete() - IUCV handler to process message completion
785  * @path:       Pending path (struct iucv_path)
786  * @msg:        Pointer to the IUCV message
787  *
788  * The function is called upon completion of message delivery to remove the
789  * message from the outqueue. Additional delivery information can be found
790  * msg->audit: rejected messages (0x040000 (IPADRJCT)), and
791  *             purged messages   (0x010000 (IPADPGNR)).
792  *
793  * Locking:     struct hvc_iucv_private->lock
794  */
795 static void hvc_iucv_msg_complete(struct iucv_path *path,
796                                   struct iucv_message *msg)
797 {
798         struct hvc_iucv_private *priv = path->private;
799         struct iucv_tty_buffer  *ent, *next;
800         LIST_HEAD(list_remove);
801
802         spin_lock(&priv->lock);
803         list_for_each_entry_safe(ent, next, &priv->tty_outqueue, list)
804                 if (ent->msg.id == msg->id) {
805                         list_move(&ent->list, &list_remove);
806                         break;
807                 }
808         wake_up(&priv->sndbuf_waitq);
809         spin_unlock(&priv->lock);
810         destroy_tty_buffer_list(&list_remove);
811 }
812
813
814 /* HVC operations */
815 static struct hv_ops hvc_iucv_ops = {
816         .get_chars = hvc_iucv_get_chars,
817         .put_chars = hvc_iucv_put_chars,
818         .notifier_add = hvc_iucv_notifier_add,
819         .notifier_del = hvc_iucv_notifier_del,
820         .notifier_hangup = hvc_iucv_notifier_hangup,
821 };
822
823 /**
824  * hvc_iucv_alloc() - Allocates a new struct hvc_iucv_private instance
825  * @id:                 hvc_iucv_table index
826  * @is_console:         Flag if the instance is used as Linux console
827  *
828  * This function allocates a new hvc_iucv_private structure and stores
829  * the instance in hvc_iucv_table at index @id.
830  * Returns 0 on success; otherwise non-zero.
831  */
832 static int __init hvc_iucv_alloc(int id, unsigned int is_console)
833 {
834         struct hvc_iucv_private *priv;
835         char name[9];
836         int rc;
837
838         priv = kzalloc(sizeof(struct hvc_iucv_private), GFP_KERNEL);
839         if (!priv)
840                 return -ENOMEM;
841
842         spin_lock_init(&priv->lock);
843         INIT_LIST_HEAD(&priv->tty_outqueue);
844         INIT_LIST_HEAD(&priv->tty_inqueue);
845         INIT_DELAYED_WORK(&priv->sndbuf_work, hvc_iucv_sndbuf_work);
846         init_waitqueue_head(&priv->sndbuf_waitq);
847
848         priv->sndbuf = (void *) get_zeroed_page(GFP_KERNEL);
849         if (!priv->sndbuf) {
850                 kfree(priv);
851                 return -ENOMEM;
852         }
853
854         /* set console flag */
855         priv->is_console = is_console;
856
857         /* finally allocate hvc */
858         priv->hvc = hvc_alloc(HVC_IUCV_MAGIC + id, /*             PAGE_SIZE */
859                               HVC_IUCV_MAGIC + id, &hvc_iucv_ops, 256);
860         if (IS_ERR(priv->hvc)) {
861                 rc = PTR_ERR(priv->hvc);
862                 free_page((unsigned long) priv->sndbuf);
863                 kfree(priv);
864                 return rc;
865         }
866
867         /* notify HVC thread instead of using polling */
868         priv->hvc->irq_requested = 1;
869
870         /* setup iucv related information */
871         snprintf(name, 9, "lnxhvc%-2d", id);
872         memcpy(priv->srv_name, name, 8);
873         ASCEBC(priv->srv_name, 8);
874
875         hvc_iucv_table[id] = priv;
876         return 0;
877 }
878
879 /**
880  * hvc_iucv_init() - z/VM IUCV HVC device driver initialization
881  */
882 static int __init hvc_iucv_init(void)
883 {
884         int rc;
885         unsigned int i;
886
887         if (!MACHINE_IS_VM) {
888                 pr_info("The z/VM IUCV HVC device driver cannot "
889                            "be used without z/VM\n");
890                 return -ENODEV;
891         }
892
893         if (!hvc_iucv_devices)
894                 return -ENODEV;
895
896         if (hvc_iucv_devices > MAX_HVC_IUCV_LINES)
897                 return -EINVAL;
898
899         hvc_iucv_buffer_cache = kmem_cache_create(KMSG_COMPONENT,
900                                            sizeof(struct iucv_tty_buffer),
901                                            0, 0, NULL);
902         if (!hvc_iucv_buffer_cache) {
903                 pr_err("Allocating memory failed with reason code=%d\n", 1);
904                 return -ENOMEM;
905         }
906
907         hvc_iucv_mempool = mempool_create_slab_pool(MEMPOOL_MIN_NR,
908                                                     hvc_iucv_buffer_cache);
909         if (!hvc_iucv_mempool) {
910                 pr_err("Allocating memory failed with reason code=%d\n", 2);
911                 kmem_cache_destroy(hvc_iucv_buffer_cache);
912                 return -ENOMEM;
913         }
914
915         /* register the first terminal device as console
916          * (must be done before allocating hvc terminal devices) */
917         rc = hvc_instantiate(HVC_IUCV_MAGIC, IUCV_HVC_CON_IDX, &hvc_iucv_ops);
918         if (rc) {
919                 pr_err("Registering HVC terminal device as "
920                        "Linux console failed\n");
921                 goto out_error_memory;
922         }
923
924         /* allocate hvc_iucv_private structs */
925         for (i = 0; i < hvc_iucv_devices; i++) {
926                 rc = hvc_iucv_alloc(i, (i == IUCV_HVC_CON_IDX) ? 1 : 0);
927                 if (rc) {
928                         pr_err("Creating a new HVC terminal device "
929                                 "failed with error code=%d\n", rc);
930                         goto out_error_hvc;
931                 }
932         }
933
934         /* register IUCV callback handler */
935         rc = iucv_register(&hvc_iucv_handler, 0);
936         if (rc) {
937                 pr_err("Registering IUCV handlers failed with error code=%d\n",
938                         rc);
939                 goto out_error_iucv;
940         }
941
942         return 0;
943
944 out_error_iucv:
945         iucv_unregister(&hvc_iucv_handler, 0);
946 out_error_hvc:
947         for (i = 0; i < hvc_iucv_devices; i++)
948                 if (hvc_iucv_table[i]) {
949                         if (hvc_iucv_table[i]->hvc)
950                                 hvc_remove(hvc_iucv_table[i]->hvc);
951                         kfree(hvc_iucv_table[i]);
952                 }
953 out_error_memory:
954         mempool_destroy(hvc_iucv_mempool);
955         kmem_cache_destroy(hvc_iucv_buffer_cache);
956         return rc;
957 }
958
959 /**
960  * hvc_iucv_config() - Parsing of hvc_iucv=  kernel command line parameter
961  * @val:        Parameter value (numeric)
962  */
963 static  int __init hvc_iucv_config(char *val)
964 {
965          return strict_strtoul(val, 10, &hvc_iucv_devices);
966 }
967
968
969 device_initcall(hvc_iucv_init);
970 __setup("hvc_iucv=", hvc_iucv_config);