]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/staging/unisys/visorchipset/visorchipset_main.c
regulator: Fix regulator_get_{optional,exclusive}() documentation
[karo-tx-linux.git] / drivers / staging / unisys / visorchipset / visorchipset_main.c
1 /* visorchipset_main.c
2  *
3  * Copyright � 2010 - 2013 UNISYS CORPORATION
4  * All rights reserved.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or (at
9  * your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
14  * NON INFRINGEMENT.  See the GNU General Public License for more
15  * details.
16  */
17
18 #include "globals.h"
19 #include "controlvm.h"
20 #include "visorchipset.h"
21 #include "procobjecttree.h"
22 #include "visorchannel.h"
23 #include "periodic_work.h"
24 #include "testing.h"
25 #include "file.h"
26 #include "parser.h"
27 #include "uniklog.h"
28 #include "uisutils.h"
29 #include "guidutils.h"
30 #include "controlvmcompletionstatus.h"
31 #include "guestlinuxdebug.h"
32 #include "filexfer.h"
33
34 #include <linux/nls.h>
35 #include <linux/netdevice.h>
36 #include <linux/platform_device.h>
37
38 #define CURRENT_FILE_PC VISOR_CHIPSET_PC_visorchipset_main_c
39 #define TEST_VNIC_PHYSITF "eth0"        /* physical network itf for
40                                          * vnic loopback test */
41 #define TEST_VNIC_SWITCHNO 1
42 #define TEST_VNIC_BUSNO 9
43
44 #define MAX_NAME_SIZE 128
45 #define MAX_IP_SIZE   50
46 #define MAXOUTSTANDINGCHANNELCOMMAND 256
47 #define POLLJIFFIES_CONTROLVMCHANNEL_FAST   1
48 #define POLLJIFFIES_CONTROLVMCHANNEL_SLOW 100
49
50 /* When the controlvm channel is idle for at least MIN_IDLE_SECONDS,
51 * we switch to slow polling mode.  As soon as we get a controlvm
52 * message, we switch back to fast polling mode.
53 */
54 #define MIN_IDLE_SECONDS 10
55 static ulong Poll_jiffies = POLLJIFFIES_CONTROLVMCHANNEL_FAST;
56 static ulong Most_recent_message_jiffies;       /* when we got our last
57                                                  * controlvm message */
58 static inline char *
59 NONULLSTR(char *s)
60 {
61         if (s)
62                 return s;
63         else
64                 return "";
65 }
66
67 static int serverregistered;
68 static int clientregistered;
69
70 #define MAX_CHIPSET_EVENTS 2
71 static U8 chipset_events[MAX_CHIPSET_EVENTS] = { 0, 0 };
72
73 static struct delayed_work Periodic_controlvm_work;
74 static struct workqueue_struct *Periodic_controlvm_workqueue;
75 static DEFINE_SEMAPHORE(NotifierLock);
76
77 typedef struct {
78         CONTROLVM_MESSAGE message;
79         unsigned int crc;
80 } MESSAGE_ENVELOPE;
81
82 static CONTROLVM_MESSAGE_HEADER g_DiagMsgHdr;
83 static CONTROLVM_MESSAGE_HEADER g_ChipSetMsgHdr;
84 static CONTROLVM_MESSAGE_HEADER g_DelDumpMsgHdr;
85 static const GUID UltraDiagPoolChannelProtocolGuid =
86         ULTRA_DIAG_POOL_CHANNEL_PROTOCOL_GUID;
87 /* 0xffffff is an invalid Bus/Device number */
88 static ulong g_diagpoolBusNo = 0xffffff;
89 static ulong g_diagpoolDevNo = 0xffffff;
90 static CONTROLVM_MESSAGE_PACKET g_DeviceChangeStatePacket;
91
92 /* Only VNIC and VHBA channels are sent to visorclientbus (aka
93  * "visorhackbus")
94  */
95 #define FOR_VISORHACKBUS(channel_type_guid) \
96         ((memcmp(&channel_type_guid, &UltraVnicChannelProtocolGuid, \
97                  sizeof(GUID)) == 0) ||                             \
98          (memcmp(&channel_type_guid, &UltraVhbaChannelProtocolGuid, \
99                  sizeof(GUID)) == 0))
100 #define FOR_VISORBUS(channel_type_guid) (!(FOR_VISORHACKBUS(channel_type_guid)))
101
102 #define is_diagpool_channel(channel_type_guid) \
103          (memcmp(&channel_type_guid, \
104                  &UltraDiagPoolChannelProtocolGuid, sizeof(GUID)) == 0)
105
106 typedef enum {
107         PARTPROP_invalid,
108         PARTPROP_name,
109         PARTPROP_description,
110         PARTPROP_handle,
111         PARTPROP_busNumber,
112         /* add new properties above, but don't forget to change
113          * InitPartitionProperties() and show_partition_property() also...
114          */
115         PARTPROP_last
116 } PARTITION_property;
117 static const char *PartitionTypeNames[] = { "partition", NULL };
118
119 static char *PartitionPropertyNames[PARTPROP_last + 1];
120 static void
121 InitPartitionProperties(void)
122 {
123         char **p = PartitionPropertyNames;
124         p[PARTPROP_invalid] = "";
125         p[PARTPROP_name] = "name";
126         p[PARTPROP_description] = "description";
127         p[PARTPROP_handle] = "handle";
128         p[PARTPROP_busNumber] = "busNumber";
129         p[PARTPROP_last] = NULL;
130 }
131
132 typedef enum {
133         CTLVMPROP_invalid,
134         CTLVMPROP_physAddr,
135         CTLVMPROP_controlChannelAddr,
136         CTLVMPROP_controlChannelBytes,
137         CTLVMPROP_sparBootPart,
138         CTLVMPROP_sparStoragePart,
139         CTLVMPROP_livedumpLength,
140         CTLVMPROP_livedumpCrc32,
141         /* add new properties above, but don't forget to change
142          * InitControlVmProperties() show_controlvm_property() also...
143          */
144         CTLVMPROP_last
145 } CONTROLVM_property;
146
147 static const char *ControlVmTypeNames[] = { "controlvm", NULL };
148
149 static char *ControlVmPropertyNames[CTLVMPROP_last + 1];
150 static void
151 InitControlVmProperties(void)
152 {
153         char **p = ControlVmPropertyNames;
154         p[CTLVMPROP_invalid] = "";
155         p[CTLVMPROP_physAddr] = "physAddr";
156         p[CTLVMPROP_controlChannelAddr] = "controlChannelAddr";
157         p[CTLVMPROP_controlChannelBytes] = "controlChannelBytes";
158         p[CTLVMPROP_sparBootPart] = "spar_boot_part";
159         p[CTLVMPROP_sparStoragePart] = "spar_storage_part";
160         p[CTLVMPROP_livedumpLength] = "livedumpLength";
161         p[CTLVMPROP_livedumpCrc32] = "livedumpCrc32";
162         p[CTLVMPROP_last] = NULL;
163 }
164
165 static MYPROCOBJECT *ControlVmObject;
166 static MYPROCTYPE *PartitionType;
167 static MYPROCTYPE *ControlVmType;
168
169 #define VISORCHIPSET_DIAG_PROC_ENTRY_FN "diagdump"
170 static struct proc_dir_entry *diag_proc_dir;
171
172 #define VISORCHIPSET_CHIPSET_PROC_ENTRY_FN "chipsetready"
173 static struct proc_dir_entry *chipset_proc_dir;
174
175 #define VISORCHIPSET_PARAHOTPLUG_PROC_ENTRY_FN "parahotplug"
176 static struct proc_dir_entry *parahotplug_proc_dir;
177
178 static LIST_HEAD(BusInfoList);
179 static LIST_HEAD(DevInfoList);
180
181 static struct proc_dir_entry *ProcDir;
182 static VISORCHANNEL *ControlVm_channel;
183
184 static ssize_t visorchipset_proc_read_writeonly(struct file *file,
185                                                 char __user *buf,
186                                                 size_t len, loff_t *offset);
187 static ssize_t proc_read_installer(struct file *file, char __user *buf,
188                                    size_t len, loff_t *offset);
189 static ssize_t proc_write_installer(struct file *file,
190                                     const char __user *buffer,
191                                     size_t count, loff_t *ppos);
192 static ssize_t proc_read_toolaction(struct file *file, char __user *buf,
193                                     size_t len, loff_t *offset);
194 static ssize_t proc_write_toolaction(struct file *file,
195                                      const char __user *buffer,
196                                      size_t count, loff_t *ppos);
197 static ssize_t proc_read_bootToTool(struct file *file, char __user *buf,
198                                     size_t len, loff_t *offset);
199 static ssize_t proc_write_bootToTool(struct file *file,
200                                      const char __user *buffer,
201                                      size_t count, loff_t *ppos);
202 static const struct file_operations proc_installer_fops = {
203         .read = proc_read_installer,
204         .write = proc_write_installer,
205 };
206
207 static const struct file_operations proc_toolaction_fops = {
208         .read = proc_read_toolaction,
209         .write = proc_write_toolaction,
210 };
211
212 static const struct file_operations proc_bootToTool_fops = {
213         .read = proc_read_bootToTool,
214         .write = proc_write_bootToTool,
215 };
216
217 typedef struct {
218         U8 __iomem *ptr;        /* pointer to base address of payload pool */
219         U64 offset;             /* offset from beginning of controlvm
220                                  * channel to beginning of payload * pool */
221         U32 bytes;              /* number of bytes in payload pool */
222 } CONTROLVM_PAYLOAD_INFO;
223
224 /* Manages the request payload in the controlvm channel */
225 static CONTROLVM_PAYLOAD_INFO ControlVm_payload_info;
226
227 static pCHANNEL_HEADER Test_Vnic_channel;
228
229 typedef struct {
230         CONTROLVM_MESSAGE_HEADER Dumpcapture_header;
231         CONTROLVM_MESSAGE_HEADER Gettextdump_header;
232         CONTROLVM_MESSAGE_HEADER Dumpcomplete_header;
233         BOOL Gettextdump_outstanding;
234         u32 crc32;
235         ulong length;
236         atomic_t buffers_in_use;
237         ulong destination;
238 } LIVEDUMP_INFO;
239 /* Manages the info for a CONTROLVM_DUMP_CAPTURESTATE /
240  * CONTROLVM_DUMP_GETTEXTDUMP / CONTROLVM_DUMP_COMPLETE conversation.
241  */
242 static LIVEDUMP_INFO LiveDump_info;
243
244 /* The following globals are used to handle the scenario where we are unable to
245  * offload the payload from a controlvm message due to memory requirements.  In
246  * this scenario, we simply stash the controlvm message, then attempt to
247  * process it again the next time controlvm_periodic_work() runs.
248  */
249 static CONTROLVM_MESSAGE ControlVm_Pending_Msg;
250 static BOOL ControlVm_Pending_Msg_Valid = FALSE;
251
252 /* Pool of struct putfile_buffer_entry, for keeping track of pending (incoming)
253  * TRANSMIT_FILE PutFile payloads.
254  */
255 static struct kmem_cache *Putfile_buffer_list_pool;
256 static const char Putfile_buffer_list_pool_name[] =
257         "controlvm_putfile_buffer_list_pool";
258
259 /* This identifies a data buffer that has been received via a controlvm messages
260  * in a remote --> local CONTROLVM_TRANSMIT_FILE conversation.
261  */
262 struct putfile_buffer_entry {
263         struct list_head next;  /* putfile_buffer_entry list */
264         PARSER_CONTEXT *parser_ctx; /* points to buffer containing input data */
265 };
266
267 /* List of struct putfile_request *, via next_putfile_request member.
268  * Each entry in this list identifies an outstanding TRANSMIT_FILE
269  * conversation.
270  */
271 static LIST_HEAD(Putfile_request_list);
272
273 /* This describes a buffer and its current state of transfer (e.g., how many
274  * bytes have already been supplied as putfile data, and how many bytes are
275  * remaining) for a putfile_request.
276  */
277 struct putfile_active_buffer {
278         /* a payload from a controlvm message, containing a file data buffer */
279         PARSER_CONTEXT *parser_ctx;
280         /* points within data area of parser_ctx to next byte of data */
281         u8 *pnext;
282         /* # bytes left from <pnext> to the end of this data buffer */
283         size_t bytes_remaining;
284 };
285
286 #define PUTFILE_REQUEST_SIG 0x0906101302281211
287 /* This identifies a single remote --> local CONTROLVM_TRANSMIT_FILE
288  * conversation.  Structs of this type are dynamically linked into
289  * <Putfile_request_list>.
290  */
291 struct putfile_request {
292         u64 sig;                /* PUTFILE_REQUEST_SIG */
293
294         /* header from original TransmitFile request */
295         CONTROLVM_MESSAGE_HEADER controlvm_header;
296         u64 file_request_number;        /* from original TransmitFile request */
297
298         /* link to next struct putfile_request */
299         struct list_head next_putfile_request;
300
301         /* most-recent sequence number supplied via a controlvm message */
302         u64 data_sequence_number;
303
304         /* head of putfile_buffer_entry list, which describes the data to be
305          * supplied as putfile data;
306          * - this list is added to when controlvm messages come in that supply
307          * file data
308          * - this list is removed from via the hotplug program that is actually
309          * consuming these buffers to write as file data */
310         struct list_head input_buffer_list;
311         spinlock_t req_list_lock;       /* lock for input_buffer_list */
312
313         /* waiters for input_buffer_list to go non-empty */
314         wait_queue_head_t input_buffer_wq;
315
316         /* data not yet read within current putfile_buffer_entry */
317         struct putfile_active_buffer active_buf;
318
319         /* <0 = failed, 0 = in-progress, >0 = successful; */
320         /* note that this must be set with req_list_lock, and if you set <0, */
321         /* it is your responsibility to also free up all of the other objects */
322         /* in this struct (like input_buffer_list, active_buf.parser_ctx) */
323         /* before releasing the lock */
324         int completion_status;
325 };
326
327 static atomic_t Visorchipset_cache_buffers_in_use = ATOMIC_INIT(0);
328
329 struct parahotplug_request {
330         struct list_head list;
331         int id;
332         unsigned long expiration;
333         CONTROLVM_MESSAGE msg;
334 };
335
336 static LIST_HEAD(Parahotplug_request_list);
337 static DEFINE_SPINLOCK(Parahotplug_request_list_lock);  /* lock for above */
338 static void parahotplug_process_list(void);
339
340 /* Manages the info for a CONTROLVM_DUMP_CAPTURESTATE /
341  * CONTROLVM_REPORTEVENT.
342  */
343 static VISORCHIPSET_BUSDEV_NOTIFIERS BusDev_Server_Notifiers;
344 static VISORCHIPSET_BUSDEV_NOTIFIERS BusDev_Client_Notifiers;
345
346 static void bus_create_response(ulong busNo, int response);
347 static void bus_destroy_response(ulong busNo, int response);
348 static void device_create_response(ulong busNo, ulong devNo, int response);
349 static void device_destroy_response(ulong busNo, ulong devNo, int response);
350 static void device_resume_response(ulong busNo, ulong devNo, int response);
351
352 static VISORCHIPSET_BUSDEV_RESPONDERS BusDev_Responders = {
353         .bus_create = bus_create_response,
354         .bus_destroy = bus_destroy_response,
355         .device_create = device_create_response,
356         .device_destroy = device_destroy_response,
357         .device_pause = visorchipset_device_pause_response,
358         .device_resume = device_resume_response,
359 };
360
361 /* info for /dev/visorchipset */
362 static dev_t MajorDev = -1; /**< indicates major num for device */
363
364 /* /sys/devices/platform/visorchipset */
365 static struct platform_device Visorchipset_platform_device = {
366         .name = "visorchipset",
367         .id = -1,
368 };
369
370 /* Function prototypes */
371 static void controlvm_respond(CONTROLVM_MESSAGE_HEADER *msgHdr, int response);
372 static void controlvm_respond_chipset_init(CONTROLVM_MESSAGE_HEADER *msgHdr,
373                                            int response,
374                                            ULTRA_CHIPSET_FEATURE features);
375 static void controlvm_respond_physdev_changestate(CONTROLVM_MESSAGE_HEADER *
376                                                   msgHdr, int response,
377                                                   ULTRA_SEGMENT_STATE state);
378
379 static void
380 show_partition_property(struct seq_file *f, void *ctx, int property)
381 {
382         VISORCHIPSET_BUS_INFO *info = (VISORCHIPSET_BUS_INFO *) (ctx);
383
384         switch (property) {
385         case PARTPROP_name:
386                 seq_printf(f, "%s\n", NONULLSTR(info->name));
387                 break;
388         case PARTPROP_description:
389                 seq_printf(f, "%s\n", NONULLSTR(info->description));
390                 break;
391         case PARTPROP_handle:
392                 seq_printf(f, "0x%-16.16Lx\n", info->partitionHandle);
393                 break;
394         case PARTPROP_busNumber:
395                 seq_printf(f, "%d\n", info->busNo);
396                 break;
397         default:
398                 seq_printf(f, "(%d??)\n", property);
399                 break;
400         }
401 }
402
403 static void
404 show_controlvm_property(struct seq_file *f, void *ctx, int property)
405 {
406         /* Note: ctx is not needed since we only have 1 controlvm channel */
407         switch (property) {
408         case CTLVMPROP_physAddr:
409                 if (ControlVm_channel == NULL)
410                         seq_puts(f, "0x0\n");
411                 else
412                         seq_printf(f, "0x%-16.16Lx\n",
413                                    visorchannel_get_physaddr
414                                    (ControlVm_channel));
415                 break;
416         case CTLVMPROP_controlChannelAddr:
417                 if (ControlVm_channel == NULL)
418                         seq_puts(f, "0x0\n");
419                 else {
420                         GUEST_PHYSICAL_ADDRESS addr = 0;
421                         visorchannel_read(ControlVm_channel,
422                                           offsetof
423                                           (ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
424                                            gpControlChannel), &addr,
425                                           sizeof(addr));
426                         seq_printf(f, "0x%-16.16Lx\n", (u64) (addr));
427                 }
428                 break;
429         case CTLVMPROP_controlChannelBytes:
430                 if (ControlVm_channel == NULL)
431                         seq_puts(f, "0x0\n");
432                 else {
433                         U32 bytes = 0;
434                         visorchannel_read(ControlVm_channel,
435                                           offsetof
436                                           (ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
437                                            ControlChannelBytes), &bytes,
438                                           sizeof(bytes));
439                         seq_printf(f, "%lu\n", (ulong) (bytes));
440                 }
441                 break;
442         case CTLVMPROP_sparBootPart:
443                 seq_puts(f, "0:0:0:0/1\n");
444                 break;
445         case CTLVMPROP_sparStoragePart:
446                 seq_puts(f, "0:0:0:0/2\n");
447                 break;
448         case CTLVMPROP_livedumpLength:
449                 seq_printf(f, "%lu\n", LiveDump_info.length);
450                 break;
451         case CTLVMPROP_livedumpCrc32:
452                 seq_printf(f, "%lu\n", (ulong) LiveDump_info.crc32);
453                 break;
454         default:
455                 seq_printf(f, "(%d??)\n", property);
456                 break;
457         }
458 }
459
460 static void
461 proc_Init(void)
462 {
463         if (ProcDir == NULL) {
464                 ProcDir = proc_mkdir(MYDRVNAME, NULL);
465                 if (ProcDir == NULL) {
466                         LOGERR("failed to create /proc directory %s",
467                                MYDRVNAME);
468                         POSTCODE_LINUX_2(CHIPSET_INIT_FAILURE_PC,
469                                          POSTCODE_SEVERITY_ERR);
470                 }
471         }
472 }
473
474 static void
475 proc_DeInit(void)
476 {
477         if (ProcDir != NULL)
478                 remove_proc_entry(MYDRVNAME, NULL);
479         ProcDir = NULL;
480 }
481
482 #if 0
483 static void
484 testUnicode(void)
485 {
486         wchar_t unicodeString[] = { 'a', 'b', 'c', 0 };
487         char s[sizeof(unicodeString) * NLS_MAX_CHARSET_SIZE];
488         wchar_t unicode2[99];
489
490         /* NOTE: Either due to a bug, or feature I don't understand, the
491          *       kernel utf8_mbstowcs() and utf_wcstombs() do NOT copy the
492          *       trailed NUL byte!!   REALLY!!!!!    Arrrrgggghhhhh
493          */
494
495         LOGINF("sizeof(wchar_t) = %d", sizeof(wchar_t));
496         LOGINF("utf8_wcstombs=%d",
497                chrs = utf8_wcstombs(s, unicodeString, sizeof(s)));
498         if (chrs >= 0)
499                 s[chrs] = '\0'; /* GRRRRRRRR */
500         LOGINF("s='%s'", s);
501         LOGINF("utf8_mbstowcs=%d", chrs = utf8_mbstowcs(unicode2, s, 100));
502         if (chrs >= 0)
503                 unicode2[chrs] = 0;     /* GRRRRRRRR */
504         if (memcmp(unicodeString, unicode2, sizeof(unicodeString)) == 0)
505                 LOGINF("strings match... good");
506         else
507                 LOGINF("strings did not match!!");
508 }
509 #endif
510
511 static void
512 busInfo_clear(void *v)
513 {
514         VISORCHIPSET_BUS_INFO *p = (VISORCHIPSET_BUS_INFO *) (v);
515
516         if (p->procObject) {
517                 visor_proc_DestroyObject(p->procObject);
518                 p->procObject = NULL;
519         }
520         kfree(p->name);
521         p->name = NULL;
522
523         kfree(p->description);
524         p->description = NULL;
525
526         p->state.created = 0;
527         memset(p, 0, sizeof(VISORCHIPSET_BUS_INFO));
528 }
529
530 static void
531 devInfo_clear(void *v)
532 {
533         VISORCHIPSET_DEVICE_INFO *p = (VISORCHIPSET_DEVICE_INFO *) (v);
534         p->state.created = 0;
535         memset(p, 0, sizeof(VISORCHIPSET_DEVICE_INFO));
536 }
537
538 static U8
539 check_chipset_events(void)
540 {
541         int i;
542         U8 send_msg = 1;
543         /* Check events to determine if response should be sent */
544         for (i = 0; i < MAX_CHIPSET_EVENTS; i++)
545                 send_msg &= chipset_events[i];
546         return send_msg;
547 }
548
549 static void
550 clear_chipset_events(void)
551 {
552         int i;
553         /* Clear chipset_events */
554         for (i = 0; i < MAX_CHIPSET_EVENTS; i++)
555                 chipset_events[i] = 0;
556 }
557
558 void
559 visorchipset_register_busdev_server(VISORCHIPSET_BUSDEV_NOTIFIERS *notifiers,
560                                     VISORCHIPSET_BUSDEV_RESPONDERS *responders,
561                                     ULTRA_VBUS_DEVICEINFO *driverInfo)
562 {
563         LOCKSEM_UNINTERRUPTIBLE(&NotifierLock);
564         if (notifiers == NULL) {
565                 memset(&BusDev_Server_Notifiers, 0,
566                        sizeof(BusDev_Server_Notifiers));
567                 serverregistered = 0;   /* clear flag */
568         } else {
569                 BusDev_Server_Notifiers = *notifiers;
570                 serverregistered = 1;   /* set flag */
571         }
572         if (responders)
573                 *responders = BusDev_Responders;
574         if (driverInfo)
575                 BusDeviceInfo_Init(driverInfo, "chipset", "visorchipset",
576                                    VERSION, NULL, __DATE__, __TIME__);
577
578         UNLOCKSEM(&NotifierLock);
579 }
580 EXPORT_SYMBOL_GPL(visorchipset_register_busdev_server);
581
582 void
583 visorchipset_register_busdev_client(VISORCHIPSET_BUSDEV_NOTIFIERS *notifiers,
584                                     VISORCHIPSET_BUSDEV_RESPONDERS *responders,
585                                     ULTRA_VBUS_DEVICEINFO *driverInfo)
586 {
587         LOCKSEM_UNINTERRUPTIBLE(&NotifierLock);
588         if (notifiers == NULL) {
589                 memset(&BusDev_Client_Notifiers, 0,
590                        sizeof(BusDev_Client_Notifiers));
591                 clientregistered = 0;   /* clear flag */
592         } else {
593                 BusDev_Client_Notifiers = *notifiers;
594                 clientregistered = 1;   /* set flag */
595         }
596         if (responders)
597                 *responders = BusDev_Responders;
598         if (driverInfo)
599                 BusDeviceInfo_Init(driverInfo, "chipset(bolts)", "visorchipset",
600                                    VERSION, NULL, __DATE__, __TIME__);
601         UNLOCKSEM(&NotifierLock);
602 }
603 EXPORT_SYMBOL_GPL(visorchipset_register_busdev_client);
604
605 static void
606 cleanup_controlvm_structures(void)
607 {
608         VISORCHIPSET_BUS_INFO *bi;
609         VISORCHIPSET_DEVICE_INFO *di;
610
611         list_for_each_entry(bi, &BusInfoList, entry) {
612                 busInfo_clear(bi);
613                 list_del(&bi->entry);
614                 kfree(bi);
615         }
616
617         list_for_each_entry(di, &DevInfoList, entry) {
618                 devInfo_clear(di);
619                 list_del(&di->entry);
620                 kfree(di);
621         }
622 }
623
624 static void
625 chipset_init(CONTROLVM_MESSAGE *inmsg)
626 {
627         static int chipset_inited;
628         ULTRA_CHIPSET_FEATURE features = 0;
629         int rc = CONTROLVM_RESP_SUCCESS;
630
631         POSTCODE_LINUX_2(CHIPSET_INIT_ENTRY_PC, POSTCODE_SEVERITY_INFO);
632         if (chipset_inited) {
633                 LOGERR("CONTROLVM_CHIPSET_INIT Failed: Already Done.");
634                 rc = -CONTROLVM_RESP_ERROR_ALREADY_DONE;
635                 goto Away;
636         }
637         chipset_inited = 1;
638         POSTCODE_LINUX_2(CHIPSET_INIT_EXIT_PC, POSTCODE_SEVERITY_INFO);
639
640         /* Set features to indicate we support parahotplug (if Command
641          * also supports it). */
642         features =
643             inmsg->cmd.initChipset.
644             features & ULTRA_CHIPSET_FEATURE_PARA_HOTPLUG;
645
646         /* Set the "reply" bit so Command knows this is a
647          * features-aware driver. */
648         features |= ULTRA_CHIPSET_FEATURE_REPLY;
649
650 Away:
651         if (rc < 0)
652                 cleanup_controlvm_structures();
653         if (inmsg->hdr.Flags.responseExpected)
654                 controlvm_respond_chipset_init(&inmsg->hdr, rc, features);
655 }
656
657 static void
658 controlvm_init_response(CONTROLVM_MESSAGE *msg,
659                         CONTROLVM_MESSAGE_HEADER *msgHdr, int response)
660 {
661         memset(msg, 0, sizeof(CONTROLVM_MESSAGE));
662         memcpy(&msg->hdr, msgHdr, sizeof(CONTROLVM_MESSAGE_HEADER));
663         msg->hdr.PayloadBytes = 0;
664         msg->hdr.PayloadVmOffset = 0;
665         msg->hdr.PayloadMaxBytes = 0;
666         if (response < 0) {
667                 msg->hdr.Flags.failed = 1;
668                 msg->hdr.CompletionStatus = (U32) (-response);
669         }
670 }
671
672 static void
673 controlvm_respond(CONTROLVM_MESSAGE_HEADER *msgHdr, int response)
674 {
675         CONTROLVM_MESSAGE outmsg;
676         if (!ControlVm_channel)
677                 return;
678         controlvm_init_response(&outmsg, msgHdr, response);
679         /* For DiagPool channel DEVICE_CHANGESTATE, we need to send
680         * back the deviceChangeState structure in the packet. */
681         if (msgHdr->Id == CONTROLVM_DEVICE_CHANGESTATE
682             && g_DeviceChangeStatePacket.deviceChangeState.busNo ==
683             g_diagpoolBusNo
684             && g_DeviceChangeStatePacket.deviceChangeState.devNo ==
685             g_diagpoolDevNo)
686                 outmsg.cmd = g_DeviceChangeStatePacket;
687         if (outmsg.hdr.Flags.testMessage == 1) {
688                 LOGINF("%s controlvm_msg=0x%x response=%d for test message",
689                        __func__, outmsg.hdr.Id, response);
690                 return;
691         }
692         if (!visorchannel_signalinsert(ControlVm_channel,
693                                        CONTROLVM_QUEUE_REQUEST, &outmsg)) {
694                 LOGERR("signalinsert failed!");
695                 return;
696         }
697 }
698
699 static void
700 controlvm_respond_chipset_init(CONTROLVM_MESSAGE_HEADER *msgHdr, int response,
701                                ULTRA_CHIPSET_FEATURE features)
702 {
703         CONTROLVM_MESSAGE outmsg;
704         if (!ControlVm_channel)
705                 return;
706         controlvm_init_response(&outmsg, msgHdr, response);
707         outmsg.cmd.initChipset.features = features;
708         if (!visorchannel_signalinsert(ControlVm_channel,
709                                        CONTROLVM_QUEUE_REQUEST, &outmsg)) {
710                 LOGERR("signalinsert failed!");
711                 return;
712         }
713 }
714
715 static void
716 controlvm_respond_physdev_changestate(CONTROLVM_MESSAGE_HEADER *msgHdr,
717                                       int response, ULTRA_SEGMENT_STATE state)
718 {
719         CONTROLVM_MESSAGE outmsg;
720         if (!ControlVm_channel)
721                 return;
722         controlvm_init_response(&outmsg, msgHdr, response);
723         outmsg.cmd.deviceChangeState.state = state;
724         outmsg.cmd.deviceChangeState.flags.physicalDevice = 1;
725         if (!visorchannel_signalinsert(ControlVm_channel,
726                                        CONTROLVM_QUEUE_REQUEST, &outmsg)) {
727                 LOGERR("signalinsert failed!");
728                 return;
729         }
730 }
731
732 void
733 visorchipset_save_message(CONTROLVM_MESSAGE *msg, CRASH_OBJ_TYPE type)
734 {
735         U32 localSavedCrashMsgOffset;
736         U16 localSavedCrashMsgCount;
737
738         /* get saved message count */
739         if (visorchannel_read(ControlVm_channel,
740                               offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
741                                        SavedCrashMsgCount),
742                               &localSavedCrashMsgCount, sizeof(U16)) < 0) {
743                 LOGERR("failed to get Saved Message Count");
744                 POSTCODE_LINUX_2(CRASH_DEV_CTRL_RD_FAILURE_PC,
745                                  POSTCODE_SEVERITY_ERR);
746                 return;
747         }
748
749         if (localSavedCrashMsgCount != CONTROLVM_CRASHMSG_MAX) {
750                 LOGERR("Saved Message Count incorrect %d",
751                        localSavedCrashMsgCount);
752                 POSTCODE_LINUX_3(CRASH_DEV_COUNT_FAILURE_PC,
753                                  localSavedCrashMsgCount,
754                                  POSTCODE_SEVERITY_ERR);
755                 return;
756         }
757
758         /* get saved crash message offset */
759         if (visorchannel_read(ControlVm_channel,
760                               offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
761                                        SavedCrashMsgOffset),
762                               &localSavedCrashMsgOffset, sizeof(U32)) < 0) {
763                 LOGERR("failed to get Saved Message Offset");
764                 POSTCODE_LINUX_2(CRASH_DEV_CTRL_RD_FAILURE_PC,
765                                  POSTCODE_SEVERITY_ERR);
766                 return;
767         }
768
769         if (type == CRASH_bus) {
770                 if (visorchannel_write(ControlVm_channel,
771                                        localSavedCrashMsgOffset,
772                                        msg, sizeof(CONTROLVM_MESSAGE)) < 0) {
773                         LOGERR("SAVE_MSG_BUS_FAILURE: Failed to write CrashCreateBusMsg!");
774                         POSTCODE_LINUX_2(SAVE_MSG_BUS_FAILURE_PC,
775                                          POSTCODE_SEVERITY_ERR);
776                         return;
777                 }
778         } else {
779                 if (visorchannel_write(ControlVm_channel,
780                                        localSavedCrashMsgOffset +
781                                        sizeof(CONTROLVM_MESSAGE), msg,
782                                        sizeof(CONTROLVM_MESSAGE)) < 0) {
783                         LOGERR("SAVE_MSG_DEV_FAILURE: Failed to write CrashCreateDevMsg!");
784                         POSTCODE_LINUX_2(SAVE_MSG_DEV_FAILURE_PC,
785                                          POSTCODE_SEVERITY_ERR);
786                         return;
787                 }
788         }
789 }
790 EXPORT_SYMBOL_GPL(visorchipset_save_message);
791
792 static void
793 bus_responder(CONTROLVM_ID cmdId, ulong busNo, int response)
794 {
795         VISORCHIPSET_BUS_INFO *p = NULL;
796         BOOL need_clear = FALSE;
797
798         p = findbus(&BusInfoList, busNo);
799         if (!p) {
800                 LOGERR("internal error busNo=%lu", busNo);
801                 return;
802         }
803         if (response < 0) {
804                 if ((cmdId == CONTROLVM_BUS_CREATE) &&
805                     (response != (-CONTROLVM_RESP_ERROR_ALREADY_DONE)))
806                         /* undo the row we just created... */
807                         delbusdevices(&DevInfoList, busNo);
808         } else {
809                 if (cmdId == CONTROLVM_BUS_CREATE)
810                         p->state.created = 1;
811                 if (cmdId == CONTROLVM_BUS_DESTROY)
812                         need_clear = TRUE;
813         }
814
815         if (p->pendingMsgHdr.Id == CONTROLVM_INVALID) {
816                 LOGERR("bus_responder no pending msg");
817                 return;         /* no controlvm response needed */
818         }
819         if (p->pendingMsgHdr.Id != (U32) cmdId) {
820                 LOGERR("expected=%d, found=%d", cmdId, p->pendingMsgHdr.Id);
821                 return;
822         }
823         controlvm_respond(&p->pendingMsgHdr, response);
824         p->pendingMsgHdr.Id = CONTROLVM_INVALID;
825         if (need_clear) {
826                 busInfo_clear(p);
827                 delbusdevices(&DevInfoList, busNo);
828         }
829 }
830
831 static void
832 device_changestate_responder(CONTROLVM_ID cmdId,
833                              ulong busNo, ulong devNo, int response,
834                              ULTRA_SEGMENT_STATE responseState)
835 {
836         VISORCHIPSET_DEVICE_INFO *p = NULL;
837         CONTROLVM_MESSAGE outmsg;
838
839         if (!ControlVm_channel)
840                 return;
841
842         p = finddevice(&DevInfoList, busNo, devNo);
843         if (!p) {
844                 LOGERR("internal error; busNo=%lu, devNo=%lu", busNo, devNo);
845                 return;
846         }
847         if (p->pendingMsgHdr.Id == CONTROLVM_INVALID) {
848                 LOGERR("device_responder no pending msg");
849                 return;         /* no controlvm response needed */
850         }
851         if (p->pendingMsgHdr.Id != cmdId) {
852                 LOGERR("expected=%d, found=%d", cmdId, p->pendingMsgHdr.Id);
853                 return;
854         }
855
856         controlvm_init_response(&outmsg, &p->pendingMsgHdr, response);
857
858         outmsg.cmd.deviceChangeState.busNo = busNo;
859         outmsg.cmd.deviceChangeState.devNo = devNo;
860         outmsg.cmd.deviceChangeState.state = responseState;
861
862         if (!visorchannel_signalinsert(ControlVm_channel,
863                                        CONTROLVM_QUEUE_REQUEST, &outmsg)) {
864                 LOGERR("signalinsert failed!");
865                 return;
866         }
867
868         p->pendingMsgHdr.Id = CONTROLVM_INVALID;
869 }
870
871 static void
872 device_responder(CONTROLVM_ID cmdId, ulong busNo, ulong devNo, int response)
873 {
874         VISORCHIPSET_DEVICE_INFO *p = NULL;
875         BOOL need_clear = FALSE;
876
877         p = finddevice(&DevInfoList, busNo, devNo);
878         if (!p) {
879                 LOGERR("internal error; busNo=%lu, devNo=%lu", busNo, devNo);
880                 return;
881         }
882         if (response >= 0) {
883                 if (cmdId == CONTROLVM_DEVICE_CREATE)
884                         p->state.created = 1;
885                 if (cmdId == CONTROLVM_DEVICE_DESTROY)
886                         need_clear = TRUE;
887         }
888
889         if (p->pendingMsgHdr.Id == CONTROLVM_INVALID) {
890                 LOGERR("device_responder no pending msg");
891                 return;         /* no controlvm response needed */
892         }
893         if (p->pendingMsgHdr.Id != (U32) cmdId) {
894                 LOGERR("expected=%d, found=%d", cmdId, p->pendingMsgHdr.Id);
895                 return;
896         }
897         controlvm_respond(&p->pendingMsgHdr, response);
898         p->pendingMsgHdr.Id = CONTROLVM_INVALID;
899         if (need_clear)
900                 devInfo_clear(p);
901 }
902
903 static void
904 bus_epilog(U32 busNo,
905            U32 cmd, CONTROLVM_MESSAGE_HEADER *msgHdr,
906            int response, BOOL needResponse)
907 {
908         BOOL notified = FALSE;
909
910         VISORCHIPSET_BUS_INFO *pBusInfo = findbus(&BusInfoList, busNo);
911
912         if (!pBusInfo) {
913                 LOGERR("HUH? bad busNo=%d", busNo);
914                 return;
915         }
916         if (needResponse) {
917                 memcpy(&pBusInfo->pendingMsgHdr, msgHdr,
918                        sizeof(CONTROLVM_MESSAGE_HEADER));
919         } else
920                 pBusInfo->pendingMsgHdr.Id = CONTROLVM_INVALID;
921
922         LOCKSEM_UNINTERRUPTIBLE(&NotifierLock);
923         if (response == CONTROLVM_RESP_SUCCESS) {
924                 switch (cmd) {
925                 case CONTROLVM_BUS_CREATE:
926                         /* We can't tell from the bus_create
927                         * information which of our 2 bus flavors the
928                         * devices on this bus will ultimately end up.
929                         * FORTUNATELY, it turns out it is harmless to
930                         * send the bus_create to both of them.  We can
931                         * narrow things down a little bit, though,
932                         * because we know: - BusDev_Server can handle
933                         * either server or client devices
934                         * - BusDev_Client can handle ONLY client
935                         * devices */
936                         if (BusDev_Server_Notifiers.bus_create) {
937                                 (*BusDev_Server_Notifiers.bus_create) (busNo);
938                                 notified = TRUE;
939                         }
940                         if ((!pBusInfo->flags.server) /*client */ &&
941                             BusDev_Client_Notifiers.bus_create) {
942                                 (*BusDev_Client_Notifiers.bus_create) (busNo);
943                                 notified = TRUE;
944                         }
945                         break;
946                 case CONTROLVM_BUS_DESTROY:
947                         if (BusDev_Server_Notifiers.bus_destroy) {
948                                 (*BusDev_Server_Notifiers.bus_destroy) (busNo);
949                                 notified = TRUE;
950                         }
951                         if ((!pBusInfo->flags.server) /*client */ &&
952                             BusDev_Client_Notifiers.bus_destroy) {
953                                 (*BusDev_Client_Notifiers.bus_destroy) (busNo);
954                                 notified = TRUE;
955                         }
956                         break;
957                 }
958         }
959         if (notified)
960                 /* The callback function just called above is responsible
961                  * for calling the appropriate VISORCHIPSET_BUSDEV_RESPONDERS
962                  * function, which will call bus_responder()
963                  */
964                 ;
965         else
966                 bus_responder(cmd, busNo, response);
967         UNLOCKSEM(&NotifierLock);
968 }
969
970 static void
971 device_epilog(U32 busNo, U32 devNo, ULTRA_SEGMENT_STATE state, U32 cmd,
972               CONTROLVM_MESSAGE_HEADER *msgHdr, int response,
973               BOOL needResponse, BOOL for_visorbus)
974 {
975         VISORCHIPSET_BUSDEV_NOTIFIERS *notifiers = NULL;
976         BOOL notified = FALSE;
977
978         VISORCHIPSET_DEVICE_INFO *pDevInfo =
979                 finddevice(&DevInfoList, busNo, devNo);
980         char *envp[] = {
981                 "SPARSP_DIAGPOOL_PAUSED_STATE = 1",
982                 NULL
983         };
984
985         if (!pDevInfo) {
986                 LOGERR("HUH? bad busNo=%d, devNo=%d", busNo, devNo);
987                 return;
988         }
989         if (for_visorbus)
990                 notifiers = &BusDev_Server_Notifiers;
991         else
992                 notifiers = &BusDev_Client_Notifiers;
993         if (needResponse) {
994                 memcpy(&pDevInfo->pendingMsgHdr, msgHdr,
995                        sizeof(CONTROLVM_MESSAGE_HEADER));
996         } else
997                 pDevInfo->pendingMsgHdr.Id = CONTROLVM_INVALID;
998
999         LOCKSEM_UNINTERRUPTIBLE(&NotifierLock);
1000         if (response >= 0) {
1001                 switch (cmd) {
1002                 case CONTROLVM_DEVICE_CREATE:
1003                         if (notifiers->device_create) {
1004                                 (*notifiers->device_create) (busNo, devNo);
1005                                 notified = TRUE;
1006                         }
1007                         break;
1008                 case CONTROLVM_DEVICE_CHANGESTATE:
1009                         /* ServerReady / ServerRunning / SegmentStateRunning */
1010                         if (state.Alive == SegmentStateRunning.Alive &&
1011                             state.Operating == SegmentStateRunning.Operating) {
1012                                 if (notifiers->device_resume) {
1013                                         (*notifiers->device_resume) (busNo,
1014                                                                      devNo);
1015                                         notified = TRUE;
1016                                 }
1017                         }
1018                         /* ServerNotReady / ServerLost / SegmentStateStandby */
1019                         else if (state.Alive == SegmentStateStandby.Alive &&
1020                                  state.Operating ==
1021                                  SegmentStateStandby.Operating) {
1022                                 /* technically this is standby case
1023                                  * where server is lost
1024                                  */
1025                                 if (notifiers->device_pause) {
1026                                         (*notifiers->device_pause) (busNo,
1027                                                                     devNo);
1028                                         notified = TRUE;
1029                                 }
1030                         } else if (state.Alive == SegmentStatePaused.Alive &&
1031                                    state.Operating ==
1032                                    SegmentStatePaused.Operating) {
1033                                 /* this is lite pause where channel is
1034                                  * still valid just 'pause' of it
1035                                  */
1036                                 if (busNo == g_diagpoolBusNo
1037                                     && devNo == g_diagpoolDevNo) {
1038                                         LOGINF("DEVICE_CHANGESTATE(DiagpoolChannel busNo=%d devNo=%d is pausing...)",
1039                                              busNo, devNo);
1040                                         /* this will trigger the
1041                                          * diag_shutdown.sh script in
1042                                          * the visorchipset hotplug */
1043                                         kobject_uevent_env
1044                                             (&Visorchipset_platform_device.dev.
1045                                              kobj, KOBJ_ONLINE, envp);
1046                                 }
1047                         }
1048                         break;
1049                 case CONTROLVM_DEVICE_DESTROY:
1050                         if (notifiers->device_destroy) {
1051                                 (*notifiers->device_destroy) (busNo, devNo);
1052                                 notified = TRUE;
1053                         }
1054                         break;
1055                 }
1056         }
1057         if (notified)
1058                 /* The callback function just called above is responsible
1059                  * for calling the appropriate VISORCHIPSET_BUSDEV_RESPONDERS
1060                  * function, which will call device_responder()
1061                  */
1062                 ;
1063         else
1064                 device_responder(cmd, busNo, devNo, response);
1065         UNLOCKSEM(&NotifierLock);
1066 }
1067
1068 static void
1069 bus_create(CONTROLVM_MESSAGE *inmsg)
1070 {
1071         CONTROLVM_MESSAGE_PACKET *cmd = &inmsg->cmd;
1072         ulong busNo = cmd->createBus.busNo;
1073         int rc = CONTROLVM_RESP_SUCCESS;
1074         VISORCHIPSET_BUS_INFO *pBusInfo = NULL;
1075
1076
1077         pBusInfo = findbus(&BusInfoList, busNo);
1078         if (pBusInfo && (pBusInfo->state.created == 1)) {
1079                 LOGERR("CONTROLVM_BUS_CREATE Failed: bus %lu already exists",
1080                        busNo);
1081                 POSTCODE_LINUX_3(BUS_CREATE_FAILURE_PC, busNo,
1082                                  POSTCODE_SEVERITY_ERR);
1083                 rc = -CONTROLVM_RESP_ERROR_ALREADY_DONE;
1084                 goto Away;
1085         }
1086         pBusInfo = kzalloc(sizeof(VISORCHIPSET_BUS_INFO), GFP_KERNEL);
1087         if (pBusInfo == NULL) {
1088                 LOGERR("CONTROLVM_BUS_CREATE Failed: bus %lu kzalloc failed",
1089                        busNo);
1090                 POSTCODE_LINUX_3(BUS_CREATE_FAILURE_PC, busNo,
1091                                  POSTCODE_SEVERITY_ERR);
1092                 rc = -CONTROLVM_RESP_ERROR_KMALLOC_FAILED;
1093                 goto Away;
1094         }
1095
1096         INIT_LIST_HEAD(&pBusInfo->entry);
1097         pBusInfo->busNo = busNo;
1098         pBusInfo->devNo = cmd->createBus.deviceCount;
1099
1100         POSTCODE_LINUX_3(BUS_CREATE_ENTRY_PC, busNo, POSTCODE_SEVERITY_INFO);
1101
1102         if (inmsg->hdr.Flags.testMessage == 1)
1103                 pBusInfo->chanInfo.addrType = ADDRTYPE_localTest;
1104         else
1105                 pBusInfo->chanInfo.addrType = ADDRTYPE_localPhysical;
1106
1107         pBusInfo->flags.server = inmsg->hdr.Flags.server;
1108         pBusInfo->chanInfo.channelAddr = cmd->createBus.channelAddr;
1109         pBusInfo->chanInfo.nChannelBytes = cmd->createBus.channelBytes;
1110         pBusInfo->chanInfo.channelTypeGuid = cmd->createBus.busDataTypeGuid;
1111         pBusInfo->chanInfo.channelInstGuid = cmd->createBus.busInstGuid;
1112
1113         list_add(&pBusInfo->entry, &BusInfoList);
1114
1115         POSTCODE_LINUX_3(BUS_CREATE_EXIT_PC, busNo, POSTCODE_SEVERITY_INFO);
1116
1117 Away:
1118         bus_epilog(busNo, CONTROLVM_BUS_CREATE, &inmsg->hdr,
1119                    rc, inmsg->hdr.Flags.responseExpected == 1);
1120 }
1121
1122 static void
1123 bus_destroy(CONTROLVM_MESSAGE *inmsg)
1124 {
1125         CONTROLVM_MESSAGE_PACKET *cmd = &inmsg->cmd;
1126         ulong busNo = cmd->destroyBus.busNo;
1127         VISORCHIPSET_BUS_INFO *pBusInfo;
1128         int rc = CONTROLVM_RESP_SUCCESS;
1129
1130         pBusInfo = findbus(&BusInfoList, busNo);
1131         if (!pBusInfo) {
1132                 LOGERR("CONTROLVM_BUS_DESTROY Failed: bus %lu invalid", busNo);
1133                 rc = -CONTROLVM_RESP_ERROR_BUS_INVALID;
1134                 goto Away;
1135         }
1136         if (pBusInfo->state.created == 0) {
1137                 LOGERR("CONTROLVM_BUS_DESTROY Failed: bus %lu already destroyed",
1138                      busNo);
1139                 rc = -CONTROLVM_RESP_ERROR_ALREADY_DONE;
1140                 goto Away;
1141         }
1142
1143 Away:
1144         bus_epilog(busNo, CONTROLVM_BUS_DESTROY, &inmsg->hdr,
1145                    rc, inmsg->hdr.Flags.responseExpected == 1);
1146 }
1147
1148 static void
1149 bus_configure(CONTROLVM_MESSAGE *inmsg, PARSER_CONTEXT *parser_ctx)
1150 {
1151         CONTROLVM_MESSAGE_PACKET *cmd = &inmsg->cmd;
1152         ulong busNo = cmd->configureBus.busNo;
1153         VISORCHIPSET_BUS_INFO *pBusInfo = NULL;
1154         int rc = CONTROLVM_RESP_SUCCESS;
1155         char s[99];
1156
1157         busNo = cmd->configureBus.busNo;
1158         POSTCODE_LINUX_3(BUS_CONFIGURE_ENTRY_PC, busNo, POSTCODE_SEVERITY_INFO);
1159
1160         pBusInfo = findbus(&BusInfoList, busNo);
1161         if (!pBusInfo) {
1162                 LOGERR("CONTROLVM_BUS_CONFIGURE Failed: bus %lu invalid",
1163                        busNo);
1164                 POSTCODE_LINUX_3(BUS_CONFIGURE_FAILURE_PC, busNo,
1165                                  POSTCODE_SEVERITY_ERR);
1166                 rc = -CONTROLVM_RESP_ERROR_BUS_INVALID;
1167                 goto Away;
1168         }
1169         if (pBusInfo->state.created == 0) {
1170                 LOGERR("CONTROLVM_BUS_CONFIGURE Failed: Invalid bus %lu - not created yet",
1171                      busNo);
1172                 POSTCODE_LINUX_3(BUS_CONFIGURE_FAILURE_PC, busNo,
1173                                  POSTCODE_SEVERITY_ERR);
1174                 rc = -CONTROLVM_RESP_ERROR_BUS_INVALID;
1175                 goto Away;
1176         }
1177         /* TBD - add this check to other commands also... */
1178         if (pBusInfo->pendingMsgHdr.Id != CONTROLVM_INVALID) {
1179                 LOGERR("CONTROLVM_BUS_CONFIGURE Failed: bus %lu MsgId=%u outstanding",
1180                      busNo, (uint) pBusInfo->pendingMsgHdr.Id);
1181                 POSTCODE_LINUX_3(BUS_CONFIGURE_FAILURE_PC, busNo,
1182                                  POSTCODE_SEVERITY_ERR);
1183                 rc = -CONTROLVM_RESP_ERROR_MESSAGE_ID_INVALID_FOR_CLIENT;
1184                 goto Away;
1185         }
1186
1187         pBusInfo->partitionHandle = cmd->configureBus.guestHandle;
1188         pBusInfo->partitionGuid = parser_id_get(parser_ctx);
1189         parser_param_start(parser_ctx, PARSERSTRING_NAME);
1190         pBusInfo->name = parser_string_get(parser_ctx);
1191
1192         visorchannel_GUID_id(&pBusInfo->partitionGuid, s);
1193         pBusInfo->procObject =
1194             visor_proc_CreateObject(PartitionType, s, (void *) (pBusInfo));
1195         if (pBusInfo->procObject == NULL) {
1196                 LOGERR("CONTROLVM_BUS_CONFIGURE Failed: busNo=%lu failed to create /proc entry",
1197                      busNo);
1198                 POSTCODE_LINUX_3(BUS_CONFIGURE_FAILURE_PC, busNo,
1199                                  POSTCODE_SEVERITY_ERR);
1200                 rc = -CONTROLVM_RESP_ERROR_KMALLOC_FAILED;
1201                 goto Away;
1202         }
1203         POSTCODE_LINUX_3(BUS_CONFIGURE_EXIT_PC, busNo, POSTCODE_SEVERITY_INFO);
1204 Away:
1205         bus_epilog(busNo, CONTROLVM_BUS_CONFIGURE, &inmsg->hdr,
1206                    rc, inmsg->hdr.Flags.responseExpected == 1);
1207 }
1208
1209 static void
1210 my_device_create(CONTROLVM_MESSAGE *inmsg)
1211 {
1212         CONTROLVM_MESSAGE_PACKET *cmd = &inmsg->cmd;
1213         ulong busNo = cmd->createDevice.busNo;
1214         ulong devNo = cmd->createDevice.devNo;
1215         VISORCHIPSET_DEVICE_INFO *pDevInfo = NULL;
1216         VISORCHIPSET_BUS_INFO *pBusInfo = NULL;
1217         int rc = CONTROLVM_RESP_SUCCESS;
1218
1219         pDevInfo = finddevice(&DevInfoList, busNo, devNo);
1220         if (pDevInfo && (pDevInfo->state.created == 1)) {
1221                 LOGERR("CONTROLVM_DEVICE_CREATE Failed: busNo=%lu, devNo=%lu already exists",
1222                      busNo, devNo);
1223                 POSTCODE_LINUX_4(DEVICE_CREATE_FAILURE_PC, devNo, busNo,
1224                                  POSTCODE_SEVERITY_ERR);
1225                 rc = -CONTROLVM_RESP_ERROR_ALREADY_DONE;
1226                 goto Away;
1227         }
1228         pBusInfo = findbus(&BusInfoList, busNo);
1229         if (!pBusInfo) {
1230                 LOGERR("CONTROLVM_DEVICE_CREATE Failed: Invalid bus %lu - out of range",
1231                      busNo);
1232                 POSTCODE_LINUX_4(DEVICE_CREATE_FAILURE_PC, devNo, busNo,
1233                                  POSTCODE_SEVERITY_ERR);
1234                 rc = -CONTROLVM_RESP_ERROR_BUS_INVALID;
1235                 goto Away;
1236         }
1237         if (pBusInfo->state.created == 0) {
1238                 LOGERR("CONTROLVM_DEVICE_CREATE Failed: Invalid bus %lu - not created yet",
1239                      busNo);
1240                 POSTCODE_LINUX_4(DEVICE_CREATE_FAILURE_PC, devNo, busNo,
1241                                  POSTCODE_SEVERITY_ERR);
1242                 rc = -CONTROLVM_RESP_ERROR_BUS_INVALID;
1243                 goto Away;
1244         }
1245         pDevInfo = kzalloc(sizeof(VISORCHIPSET_DEVICE_INFO), GFP_KERNEL);
1246         if (pDevInfo == NULL) {
1247                 LOGERR("CONTROLVM_DEVICE_CREATE Failed: busNo=%lu, devNo=%lu kmaloc failed",
1248                      busNo, devNo);
1249                 POSTCODE_LINUX_4(DEVICE_CREATE_FAILURE_PC, devNo, busNo,
1250                                  POSTCODE_SEVERITY_ERR);
1251                 rc = -CONTROLVM_RESP_ERROR_KMALLOC_FAILED;
1252                 goto Away;
1253         }
1254
1255         INIT_LIST_HEAD(&pDevInfo->entry);
1256         pDevInfo->busNo = busNo;
1257         pDevInfo->devNo = devNo;
1258         pDevInfo->devInstGuid = cmd->createDevice.devInstGuid;
1259         POSTCODE_LINUX_4(DEVICE_CREATE_ENTRY_PC, devNo, busNo,
1260                          POSTCODE_SEVERITY_INFO);
1261
1262         if (inmsg->hdr.Flags.testMessage == 1)
1263                 pDevInfo->chanInfo.addrType = ADDRTYPE_localTest;
1264         else
1265                 pDevInfo->chanInfo.addrType = ADDRTYPE_localPhysical;
1266         pDevInfo->chanInfo.channelAddr = cmd->createDevice.channelAddr;
1267         pDevInfo->chanInfo.nChannelBytes = cmd->createDevice.channelBytes;
1268         pDevInfo->chanInfo.channelTypeGuid = cmd->createDevice.dataTypeGuid;
1269         pDevInfo->chanInfo.intr = cmd->createDevice.intr;
1270         list_add(&pDevInfo->entry, &DevInfoList);
1271         POSTCODE_LINUX_4(DEVICE_CREATE_EXIT_PC, devNo, busNo,
1272                          POSTCODE_SEVERITY_INFO);
1273 Away:
1274         /* get the bus and devNo for DiagPool channel */
1275         if (is_diagpool_channel(pDevInfo->chanInfo.channelTypeGuid)) {
1276                 g_diagpoolBusNo = busNo;
1277                 g_diagpoolDevNo = devNo;
1278                 LOGINF("CONTROLVM_DEVICE_CREATE for DiagPool channel: busNo=%lu, devNo=%lu",
1279                      g_diagpoolBusNo, g_diagpoolDevNo);
1280         }
1281         device_epilog(busNo, devNo, SegmentStateRunning,
1282                       CONTROLVM_DEVICE_CREATE, &inmsg->hdr, rc,
1283                       inmsg->hdr.Flags.responseExpected == 1,
1284                       FOR_VISORBUS(pDevInfo->chanInfo.channelTypeGuid));
1285 }
1286
1287 static void
1288 my_device_changestate(CONTROLVM_MESSAGE *inmsg)
1289 {
1290         CONTROLVM_MESSAGE_PACKET *cmd = &inmsg->cmd;
1291         ulong busNo = cmd->deviceChangeState.busNo;
1292         ulong devNo = cmd->deviceChangeState.devNo;
1293         ULTRA_SEGMENT_STATE state = cmd->deviceChangeState.state;
1294         VISORCHIPSET_DEVICE_INFO *pDevInfo = NULL;
1295         int rc = CONTROLVM_RESP_SUCCESS;
1296
1297         pDevInfo = finddevice(&DevInfoList, busNo, devNo);
1298         if (!pDevInfo) {
1299                 LOGERR("CONTROLVM_DEVICE_CHANGESTATE Failed: busNo=%lu, devNo=%lu invalid (doesn't exist)",
1300                      busNo, devNo);
1301                 POSTCODE_LINUX_4(DEVICE_CHANGESTATE_FAILURE_PC, devNo, busNo,
1302                                  POSTCODE_SEVERITY_ERR);
1303                 rc = -CONTROLVM_RESP_ERROR_DEVICE_INVALID;
1304                 goto Away;
1305         }
1306         if (pDevInfo->state.created == 0) {
1307                 LOGERR("CONTROLVM_DEVICE_CHANGESTATE Failed: busNo=%lu, devNo=%lu invalid (not created)",
1308                      busNo, devNo);
1309                 POSTCODE_LINUX_4(DEVICE_CHANGESTATE_FAILURE_PC, devNo, busNo,
1310                                  POSTCODE_SEVERITY_ERR);
1311                 rc = -CONTROLVM_RESP_ERROR_DEVICE_INVALID;
1312         }
1313 Away:
1314         if ((rc >= CONTROLVM_RESP_SUCCESS) && pDevInfo)
1315                 device_epilog(busNo, devNo, state, CONTROLVM_DEVICE_CHANGESTATE,
1316                               &inmsg->hdr, rc,
1317                               inmsg->hdr.Flags.responseExpected == 1,
1318                               FOR_VISORBUS(pDevInfo->chanInfo.channelTypeGuid));
1319 }
1320
1321 static void
1322 my_device_destroy(CONTROLVM_MESSAGE *inmsg)
1323 {
1324         CONTROLVM_MESSAGE_PACKET *cmd = &inmsg->cmd;
1325         ulong busNo = cmd->destroyDevice.busNo;
1326         ulong devNo = cmd->destroyDevice.devNo;
1327         VISORCHIPSET_DEVICE_INFO *pDevInfo = NULL;
1328         int rc = CONTROLVM_RESP_SUCCESS;
1329
1330         pDevInfo = finddevice(&DevInfoList, busNo, devNo);
1331         if (!pDevInfo) {
1332                 LOGERR("CONTROLVM_DEVICE_DESTROY Failed: busNo=%lu, devNo=%lu invalid",
1333                      busNo, devNo);
1334                 rc = -CONTROLVM_RESP_ERROR_DEVICE_INVALID;
1335                 goto Away;
1336         }
1337         if (pDevInfo->state.created == 0) {
1338                 LOGERR("CONTROLVM_DEVICE_DESTROY Failed: busNo=%lu, devNo=%lu already destroyed",
1339                      busNo, devNo);
1340                 rc = -CONTROLVM_RESP_ERROR_ALREADY_DONE;
1341         }
1342
1343 Away:
1344         if ((rc >= CONTROLVM_RESP_SUCCESS) && pDevInfo)
1345                 device_epilog(busNo, devNo, SegmentStateRunning,
1346                               CONTROLVM_DEVICE_DESTROY, &inmsg->hdr, rc,
1347                               inmsg->hdr.Flags.responseExpected == 1,
1348                               FOR_VISORBUS(pDevInfo->chanInfo.channelTypeGuid));
1349 }
1350
1351 /* When provided with the physical address of the controlvm channel
1352  * (phys_addr), the offset to the payload area we need to manage
1353  * (offset), and the size of this payload area (bytes), fills in the
1354  * CONTROLVM_PAYLOAD_INFO struct.  Returns TRUE for success or FALSE
1355  * for failure.
1356  */
1357 static int
1358 initialize_controlvm_payload_info(HOSTADDRESS phys_addr, U64 offset, U32 bytes,
1359                                   CONTROLVM_PAYLOAD_INFO *info)
1360 {
1361         U8 __iomem *payload = NULL;
1362         int rc = CONTROLVM_RESP_SUCCESS;
1363
1364         if (info == NULL) {
1365                 LOGERR("HUH ? CONTROLVM_PAYLOAD_INIT Failed : Programmer check at %s:%d",
1366                      __FILE__, __LINE__);
1367                 rc = -CONTROLVM_RESP_ERROR_PAYLOAD_INVALID;
1368                 goto Away;
1369         }
1370         memset(info, 0, sizeof(CONTROLVM_PAYLOAD_INFO));
1371         if ((offset == 0) || (bytes == 0)) {
1372                 LOGERR("CONTROLVM_PAYLOAD_INIT Failed: RequestPayloadOffset=%llu RequestPayloadBytes=%llu!",
1373                      (u64) offset, (u64) bytes);
1374                 rc = -CONTROLVM_RESP_ERROR_PAYLOAD_INVALID;
1375                 goto Away;
1376         }
1377         payload = ioremap_cache(phys_addr + offset, bytes);
1378         if (payload == NULL) {
1379                 LOGERR("CONTROLVM_PAYLOAD_INIT Failed: ioremap_cache %llu for %llu bytes failed",
1380                      (u64) offset, (u64) bytes);
1381                 rc = -CONTROLVM_RESP_ERROR_IOREMAP_FAILED;
1382                 goto Away;
1383         }
1384
1385         info->offset = offset;
1386         info->bytes = bytes;
1387         info->ptr = payload;
1388         LOGINF("offset=%llu, bytes=%lu, ptr=%p",
1389                (u64) (info->offset), (ulong) (info->bytes), info->ptr);
1390
1391 Away:
1392         if (rc < 0) {
1393                 if (payload != NULL) {
1394                         iounmap(payload);
1395                         payload = NULL;
1396                 }
1397         }
1398         return rc;
1399 }
1400
1401 static void
1402 destroy_controlvm_payload_info(CONTROLVM_PAYLOAD_INFO *info)
1403 {
1404         if (info->ptr != NULL) {
1405                 iounmap(info->ptr);
1406                 info->ptr = NULL;
1407         }
1408         memset(info, 0, sizeof(CONTROLVM_PAYLOAD_INFO));
1409 }
1410
1411 static void
1412 initialize_controlvm_payload(void)
1413 {
1414         HOSTADDRESS phys_addr = visorchannel_get_physaddr(ControlVm_channel);
1415         U64 payloadOffset = 0;
1416         U32 payloadBytes = 0;
1417         if (visorchannel_read(ControlVm_channel,
1418                               offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
1419                                        RequestPayloadOffset),
1420                               &payloadOffset, sizeof(payloadOffset)) < 0) {
1421                 LOGERR("CONTROLVM_PAYLOAD_INIT Failed to read controlvm channel!");
1422                 POSTCODE_LINUX_2(CONTROLVM_INIT_FAILURE_PC,
1423                                  POSTCODE_SEVERITY_ERR);
1424                 return;
1425         }
1426         if (visorchannel_read(ControlVm_channel,
1427                               offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
1428                                        RequestPayloadBytes),
1429                               &payloadBytes, sizeof(payloadBytes)) < 0) {
1430                 LOGERR("CONTROLVM_PAYLOAD_INIT Failed to read controlvm channel!");
1431                 POSTCODE_LINUX_2(CONTROLVM_INIT_FAILURE_PC,
1432                                  POSTCODE_SEVERITY_ERR);
1433                 return;
1434         }
1435         initialize_controlvm_payload_info(phys_addr,
1436                                           payloadOffset, payloadBytes,
1437                                           &ControlVm_payload_info);
1438 }
1439
1440 /*  Send ACTION=online for DEVPATH=/sys/devices/platform/visorchipset.
1441  *  Returns CONTROLVM_RESP_xxx code.
1442  */
1443 int
1444 visorchipset_chipset_ready(void)
1445 {
1446         kobject_uevent(&Visorchipset_platform_device.dev.kobj, KOBJ_ONLINE);
1447         return CONTROLVM_RESP_SUCCESS;
1448 }
1449 EXPORT_SYMBOL_GPL(visorchipset_chipset_ready);
1450
1451 int
1452 visorchipset_chipset_selftest(void)
1453 {
1454         char env_selftest[20];
1455         char *envp[] = { env_selftest, NULL };
1456         sprintf(env_selftest, "SPARSP_SELFTEST=%d", 1);
1457         kobject_uevent_env(&Visorchipset_platform_device.dev.kobj, KOBJ_CHANGE,
1458                            envp);
1459         return CONTROLVM_RESP_SUCCESS;
1460 }
1461 EXPORT_SYMBOL_GPL(visorchipset_chipset_selftest);
1462
1463 /*  Send ACTION=offline for DEVPATH=/sys/devices/platform/visorchipset.
1464  *  Returns CONTROLVM_RESP_xxx code.
1465  */
1466 int
1467 visorchipset_chipset_notready(void)
1468 {
1469         kobject_uevent(&Visorchipset_platform_device.dev.kobj, KOBJ_OFFLINE);
1470         return CONTROLVM_RESP_SUCCESS;
1471 }
1472 EXPORT_SYMBOL_GPL(visorchipset_chipset_notready);
1473
1474 static void
1475 chipset_ready(CONTROLVM_MESSAGE_HEADER *msgHdr)
1476 {
1477         int rc = visorchipset_chipset_ready();
1478         if (rc != CONTROLVM_RESP_SUCCESS)
1479                 rc = -rc;
1480         if (msgHdr->Flags.responseExpected && !visorchipset_holdchipsetready)
1481                 controlvm_respond(msgHdr, rc);
1482         if (msgHdr->Flags.responseExpected && visorchipset_holdchipsetready) {
1483                 /* Send CHIPSET_READY response when all modules have been loaded
1484                  * and disks mounted for the partition
1485                  */
1486                 g_ChipSetMsgHdr = *msgHdr;
1487                 LOGINF("Holding CHIPSET_READY response");
1488         }
1489 }
1490
1491 static void
1492 chipset_selftest(CONTROLVM_MESSAGE_HEADER *msgHdr)
1493 {
1494         int rc = visorchipset_chipset_selftest();
1495         if (rc != CONTROLVM_RESP_SUCCESS)
1496                 rc = -rc;
1497         if (msgHdr->Flags.responseExpected)
1498                 controlvm_respond(msgHdr, rc);
1499 }
1500
1501 static void
1502 chipset_notready(CONTROLVM_MESSAGE_HEADER *msgHdr)
1503 {
1504         int rc = visorchipset_chipset_notready();
1505         if (rc != CONTROLVM_RESP_SUCCESS)
1506                 rc = -rc;
1507         if (msgHdr->Flags.responseExpected)
1508                 controlvm_respond(msgHdr, rc);
1509 }
1510
1511 /* This is your "one-stop" shop for grabbing the next message from the
1512  * CONTROLVM_QUEUE_EVENT queue in the controlvm channel.
1513  */
1514 static BOOL
1515 read_controlvm_event(CONTROLVM_MESSAGE *msg)
1516 {
1517         if (visorchannel_signalremove(ControlVm_channel,
1518                                       CONTROLVM_QUEUE_EVENT, msg)) {
1519                 /* got a message */
1520                 if (msg->hdr.Flags.testMessage == 1) {
1521                         LOGERR("ignoring bad CONTROLVM_QUEUE_EVENT msg with controlvm_msg_id=0x%x because Flags.testMessage is nonsensical (=1)", msg->hdr.Id);
1522                         return FALSE;
1523                 } else
1524                         return TRUE;
1525         }
1526         return FALSE;
1527 }
1528
1529 /*
1530  * The general parahotplug flow works as follows.  The visorchipset
1531  * driver receives a DEVICE_CHANGESTATE message from Command
1532  * specifying a physical device to enable or disable.  The CONTROLVM
1533  * message handler calls parahotplug_process_message, which then adds
1534  * the message to a global list and kicks off a udev event which
1535  * causes a user level script to enable or disable the specified
1536  * device.  The udev script then writes to
1537  * /proc/visorchipset/parahotplug, which causes parahotplug_proc_write
1538  * to get called, at which point the appropriate CONTROLVM message is
1539  * retrieved from the list and responded to.
1540  */
1541
1542 #define PARAHOTPLUG_TIMEOUT_MS 2000
1543
1544 /*
1545  * Generate unique int to match an outstanding CONTROLVM message with a
1546  * udev script /proc response
1547  */
1548 static int
1549 parahotplug_next_id(void)
1550 {
1551         static atomic_t id = ATOMIC_INIT(0);
1552         return atomic_inc_return(&id);
1553 }
1554
1555 /*
1556  * Returns the time (in jiffies) when a CONTROLVM message on the list
1557  * should expire -- PARAHOTPLUG_TIMEOUT_MS in the future
1558  */
1559 static unsigned long
1560 parahotplug_next_expiration(void)
1561 {
1562         return jiffies + PARAHOTPLUG_TIMEOUT_MS * HZ / 1000;
1563 }
1564
1565 /*
1566  * Create a parahotplug_request, which is basically a wrapper for a
1567  * CONTROLVM_MESSAGE that we can stick on a list
1568  */
1569 static struct parahotplug_request *
1570 parahotplug_request_create(CONTROLVM_MESSAGE *msg)
1571 {
1572         struct parahotplug_request *req =
1573             kmalloc(sizeof(struct parahotplug_request),
1574                     GFP_KERNEL|__GFP_NORETRY);
1575         if (req == NULL)
1576                 return NULL;
1577
1578         req->id = parahotplug_next_id();
1579         req->expiration = parahotplug_next_expiration();
1580         req->msg = *msg;
1581
1582         return req;
1583 }
1584
1585 /*
1586  * Free a parahotplug_request.
1587  */
1588 static void
1589 parahotplug_request_destroy(struct parahotplug_request *req)
1590 {
1591         kfree(req);
1592 }
1593
1594 /*
1595  * Cause uevent to run the user level script to do the disable/enable
1596  * specified in (the CONTROLVM message in) the specified
1597  * parahotplug_request
1598  */
1599 static void
1600 parahotplug_request_kickoff(struct parahotplug_request *req)
1601 {
1602         CONTROLVM_MESSAGE_PACKET *cmd = &req->msg.cmd;
1603         char env_cmd[40], env_id[40], env_state[40], env_bus[40], env_dev[40],
1604             env_func[40];
1605         char *envp[] = {
1606                 env_cmd, env_id, env_state, env_bus, env_dev, env_func, NULL
1607         };
1608
1609         sprintf(env_cmd, "SPAR_PARAHOTPLUG=1");
1610         sprintf(env_id, "SPAR_PARAHOTPLUG_ID=%d", req->id);
1611         sprintf(env_state, "SPAR_PARAHOTPLUG_STATE=%d",
1612                 cmd->deviceChangeState.state.Active);
1613         sprintf(env_bus, "SPAR_PARAHOTPLUG_BUS=%d",
1614                 cmd->deviceChangeState.busNo);
1615         sprintf(env_dev, "SPAR_PARAHOTPLUG_DEVICE=%d",
1616                 cmd->deviceChangeState.devNo >> 3);
1617         sprintf(env_func, "SPAR_PARAHOTPLUG_FUNCTION=%d",
1618                 cmd->deviceChangeState.devNo & 0x7);
1619
1620         LOGINF("parahotplug_request_kickoff: state=%d, bdf=%d/%d/%d, id=%u\n",
1621                cmd->deviceChangeState.state.Active,
1622                cmd->deviceChangeState.busNo, cmd->deviceChangeState.devNo >> 3,
1623                cmd->deviceChangeState.devNo & 7, req->id);
1624
1625         kobject_uevent_env(&Visorchipset_platform_device.dev.kobj, KOBJ_CHANGE,
1626                            envp);
1627 }
1628
1629 /*
1630  * Remove any request from the list that's been on there too long and
1631  * respond with an error.
1632  */
1633 static void
1634 parahotplug_process_list(void)
1635 {
1636         struct list_head *pos = NULL;
1637         struct list_head *tmp = NULL;
1638
1639         spin_lock(&Parahotplug_request_list_lock);
1640
1641         list_for_each_safe(pos, tmp, &Parahotplug_request_list) {
1642                 struct parahotplug_request *req =
1643                     list_entry(pos, struct parahotplug_request, list);
1644                 if (time_after_eq(jiffies, req->expiration)) {
1645                         list_del(pos);
1646                         if (req->msg.hdr.Flags.responseExpected)
1647                                 controlvm_respond_physdev_changestate(
1648                                         &req->msg.hdr,
1649                                         CONTROLVM_RESP_ERROR_DEVICE_UDEV_TIMEOUT,
1650                                         req->msg.cmd.deviceChangeState.state);
1651                         parahotplug_request_destroy(req);
1652                 }
1653         }
1654
1655         spin_unlock(&Parahotplug_request_list_lock);
1656 }
1657
1658 /*
1659  * Called from the /proc handler, which means the user script has
1660  * finished the enable/disable.  Find the matching identifier, and
1661  * respond to the CONTROLVM message with success.
1662  */
1663 static int
1664 parahotplug_request_complete(int id, U16 active)
1665 {
1666         struct list_head *pos = NULL;
1667         struct list_head *tmp = NULL;
1668
1669         spin_lock(&Parahotplug_request_list_lock);
1670
1671         /* Look for a request matching "id". */
1672         list_for_each_safe(pos, tmp, &Parahotplug_request_list) {
1673                 struct parahotplug_request *req =
1674                     list_entry(pos, struct parahotplug_request, list);
1675                 if (req->id == id) {
1676                         /* Found a match.  Remove it from the list and
1677                          * respond.
1678                          */
1679                         list_del(pos);
1680                         spin_unlock(&Parahotplug_request_list_lock);
1681                         req->msg.cmd.deviceChangeState.state.Active = active;
1682                         if (req->msg.hdr.Flags.responseExpected)
1683                                 controlvm_respond_physdev_changestate(
1684                                         &req->msg.hdr, CONTROLVM_RESP_SUCCESS,
1685                                         req->msg.cmd.deviceChangeState.state);
1686                         parahotplug_request_destroy(req);
1687                         return 0;
1688                 }
1689         }
1690
1691         spin_unlock(&Parahotplug_request_list_lock);
1692         return -1;
1693 }
1694
1695 /*
1696  * Enables or disables a PCI device by kicking off a udev script
1697  */
1698 static void
1699 parahotplug_process_message(CONTROLVM_MESSAGE *inmsg)
1700 {
1701         struct parahotplug_request *req;
1702
1703         req = parahotplug_request_create(inmsg);
1704
1705         if (req == NULL) {
1706                 LOGERR("parahotplug_process_message: couldn't allocate request");
1707                 return;
1708         }
1709
1710         if (inmsg->cmd.deviceChangeState.state.Active) {
1711                 /* For enable messages, just respond with success
1712                 * right away.  This is a bit of a hack, but there are
1713                 * issues with the early enable messages we get (with
1714                 * either the udev script not detecting that the device
1715                 * is up, or not getting called at all).  Fortunately
1716                 * the messages that get lost don't matter anyway, as
1717                 * devices are automatically enabled at
1718                 * initialization.
1719                 */
1720                 parahotplug_request_kickoff(req);
1721                 controlvm_respond_physdev_changestate(&inmsg->hdr,
1722                                                       CONTROLVM_RESP_SUCCESS,
1723                                                       inmsg->cmd.
1724                                                       deviceChangeState.state);
1725                 parahotplug_request_destroy(req);
1726         } else {
1727                 /* For disable messages, add the request to the
1728                 * request list before kicking off the udev script.  It
1729                 * won't get responded to until the script has
1730                 * indicated it's done.
1731                 */
1732                 spin_lock(&Parahotplug_request_list_lock);
1733                 list_add_tail(&(req->list), &Parahotplug_request_list);
1734                 spin_unlock(&Parahotplug_request_list_lock);
1735
1736                 parahotplug_request_kickoff(req);
1737         }
1738 }
1739
1740 /*
1741  * Gets called when the udev script writes to
1742  * /proc/visorchipset/parahotplug.  Expects input in the form of "<id>
1743  * <active>" where <id> is the identifier passed to the script that
1744  * matches a request on the request list, and <active> is 0 or 1
1745  * indicating whether the device is now enabled or not.
1746  */
1747 static ssize_t
1748 parahotplug_proc_write(struct file *file, const char __user *buffer,
1749                        size_t count, loff_t *ppos)
1750 {
1751         char buf[64];
1752         uint id;
1753         ushort active;
1754
1755         if (count > sizeof(buf) - 1) {
1756                 LOGERR("parahotplug_proc_write: count (%d) exceeds size of buffer (%d)",
1757                      (int) count, (int) sizeof(buf));
1758                 return -EINVAL;
1759         }
1760         if (copy_from_user(buf, buffer, count)) {
1761                 LOGERR("parahotplug_proc_write: copy_from_user failed");
1762                 return -EFAULT;
1763         }
1764         buf[count] = '\0';
1765
1766         if (sscanf(buf, "%u %hu", &id, &active) != 2) {
1767                 id = 0;
1768                 active = 0;
1769         }
1770
1771         if (active != 1 && active != 0) {
1772                 LOGERR("parahotplug_proc_write: invalid active field");
1773                 return -EINVAL;
1774         }
1775
1776         parahotplug_request_complete((int) id, (U16) active);
1777
1778         return count;
1779 }
1780
1781 static const struct file_operations parahotplug_proc_fops = {
1782         .owner = THIS_MODULE,
1783         .read = visorchipset_proc_read_writeonly,
1784         .write = parahotplug_proc_write,
1785 };
1786
1787 /* Process a controlvm message.
1788  * Return result:
1789  *    FALSE - this function will return FALSE only in the case where the
1790  *            controlvm message was NOT processed, but processing must be
1791  *            retried before reading the next controlvm message; a
1792  *            scenario where this can occur is when we need to throttle
1793  *            the allocation of memory in which to copy out controlvm
1794  *            payload data
1795  *    TRUE  - processing of the controlvm message completed,
1796  *            either successfully or with an error.
1797  */
1798 static BOOL
1799 handle_command(CONTROLVM_MESSAGE inmsg, HOSTADDRESS channel_addr)
1800 {
1801         CONTROLVM_MESSAGE_PACKET *cmd = &inmsg.cmd;
1802         U64 parametersAddr = 0;
1803         U32 parametersBytes = 0;
1804         PARSER_CONTEXT *parser_ctx = NULL;
1805         BOOL isLocalAddr = FALSE;
1806         CONTROLVM_MESSAGE ackmsg;
1807
1808         /* create parsing context if necessary */
1809         isLocalAddr = (inmsg.hdr.Flags.testMessage == 1);
1810         if (channel_addr == 0) {
1811                 LOGERR("HUH? channel_addr is 0!");
1812                 return TRUE;
1813         }
1814         parametersAddr = channel_addr + inmsg.hdr.PayloadVmOffset;
1815         parametersBytes = inmsg.hdr.PayloadBytes;
1816
1817         /* Parameter and channel addresses within test messages actually lie
1818          * within our OS-controlled memory.  We need to know that, because it
1819          * makes a difference in how we compute the virtual address.
1820          */
1821         if (parametersAddr != 0 && parametersBytes != 0) {
1822                 BOOL retry = FALSE;
1823                 parser_ctx =
1824                     parser_init_byteStream(parametersAddr, parametersBytes,
1825                                            isLocalAddr, &retry);
1826                 if (!parser_ctx) {
1827                         if (retry) {
1828                                 LOGWRN("throttling to copy payload");
1829                                 return FALSE;
1830                         }
1831                         LOGWRN("parsing failed");
1832                         LOGWRN("inmsg.hdr.Id=0x%lx", (ulong) inmsg.hdr.Id);
1833                         LOGWRN("parametersAddr=0x%llx", (u64) parametersAddr);
1834                         LOGWRN("parametersBytes=%lu", (ulong) parametersBytes);
1835                         LOGWRN("isLocalAddr=%d", isLocalAddr);
1836                 }
1837         }
1838
1839         if (!isLocalAddr) {
1840                 controlvm_init_response(&ackmsg, &inmsg.hdr,
1841                                         CONTROLVM_RESP_SUCCESS);
1842                 if ((ControlVm_channel)
1843                     &&
1844                     (!visorchannel_signalinsert
1845                      (ControlVm_channel, CONTROLVM_QUEUE_ACK, &ackmsg)))
1846                         LOGWRN("failed to send ACK failed");
1847         }
1848         switch (inmsg.hdr.Id) {
1849         case CONTROLVM_CHIPSET_INIT:
1850                 LOGINF("CHIPSET_INIT(#busses=%lu,#switches=%lu)",
1851                        (ulong) inmsg.cmd.initChipset.busCount,
1852                        (ulong) inmsg.cmd.initChipset.switchCount);
1853                 chipset_init(&inmsg);
1854                 break;
1855         case CONTROLVM_BUS_CREATE:
1856                 LOGINF("BUS_CREATE(%lu,#devs=%lu)",
1857                        (ulong) cmd->createBus.busNo,
1858                        (ulong) cmd->createBus.deviceCount);
1859                 bus_create(&inmsg);
1860                 break;
1861         case CONTROLVM_BUS_DESTROY:
1862                 LOGINF("BUS_DESTROY(%lu)", (ulong) cmd->destroyBus.busNo);
1863                 bus_destroy(&inmsg);
1864                 break;
1865         case CONTROLVM_BUS_CONFIGURE:
1866                 LOGINF("BUS_CONFIGURE(%lu)", (ulong) cmd->configureBus.busNo);
1867                 bus_configure(&inmsg, parser_ctx);
1868                 break;
1869         case CONTROLVM_DEVICE_CREATE:
1870                 LOGINF("DEVICE_CREATE(%lu,%lu)",
1871                        (ulong) cmd->createDevice.busNo,
1872                        (ulong) cmd->createDevice.devNo);
1873                 my_device_create(&inmsg);
1874                 break;
1875         case CONTROLVM_DEVICE_CHANGESTATE:
1876                 if (cmd->deviceChangeState.flags.physicalDevice) {
1877                         LOGINF("DEVICE_CHANGESTATE for physical device (%lu,%lu, active=%lu)",
1878                              (ulong) cmd->deviceChangeState.busNo,
1879                              (ulong) cmd->deviceChangeState.devNo,
1880                              (ulong) cmd->deviceChangeState.state.Active);
1881                         parahotplug_process_message(&inmsg);
1882                 } else {
1883                         LOGINF("DEVICE_CHANGESTATE for virtual device (%lu,%lu, state.Alive=0x%lx)",
1884                              (ulong) cmd->deviceChangeState.busNo,
1885                              (ulong) cmd->deviceChangeState.devNo,
1886                              (ulong) cmd->deviceChangeState.state.Alive);
1887                         /* save the hdr and cmd structures for later use */
1888                         /* when sending back the response to Command */
1889                         my_device_changestate(&inmsg);
1890                         g_DiagMsgHdr = inmsg.hdr;
1891                         g_DeviceChangeStatePacket = inmsg.cmd;
1892                         break;
1893                 }
1894                 break;
1895         case CONTROLVM_DEVICE_DESTROY:
1896                 LOGINF("DEVICE_DESTROY(%lu,%lu)",
1897                        (ulong) cmd->destroyDevice.busNo,
1898                        (ulong) cmd->destroyDevice.devNo);
1899                 my_device_destroy(&inmsg);
1900                 break;
1901         case CONTROLVM_DEVICE_CONFIGURE:
1902                 LOGINF("DEVICE_CONFIGURE(%lu,%lu)",
1903                        (ulong) cmd->configureDevice.busNo,
1904                        (ulong) cmd->configureDevice.devNo);
1905                 /* no op for now, just send a respond that we passed */
1906                 if (inmsg.hdr.Flags.responseExpected)
1907                         controlvm_respond(&inmsg.hdr, CONTROLVM_RESP_SUCCESS);
1908                 break;
1909         case CONTROLVM_CHIPSET_READY:
1910                 LOGINF("CHIPSET_READY");
1911                 chipset_ready(&inmsg.hdr);
1912                 break;
1913         case CONTROLVM_CHIPSET_SELFTEST:
1914                 LOGINF("CHIPSET_SELFTEST");
1915                 chipset_selftest(&inmsg.hdr);
1916                 break;
1917         case CONTROLVM_CHIPSET_STOP:
1918                 LOGINF("CHIPSET_STOP");
1919                 chipset_notready(&inmsg.hdr);
1920                 break;
1921         default:
1922                 LOGERR("unrecognized controlvm cmd=%d", (int) inmsg.hdr.Id);
1923                 if (inmsg.hdr.Flags.responseExpected)
1924                         controlvm_respond(&inmsg.hdr,
1925                                           -CONTROLVM_RESP_ERROR_MESSAGE_ID_UNKNOWN);
1926                 break;
1927         }
1928
1929         if (parser_ctx != NULL) {
1930                 parser_done(parser_ctx);
1931                 parser_ctx = NULL;
1932         }
1933         return TRUE;
1934 }
1935
1936 static void
1937 controlvm_periodic_work(struct work_struct *work)
1938 {
1939         VISORCHIPSET_CHANNEL_INFO chanInfo;
1940         CONTROLVM_MESSAGE inmsg;
1941         char s[99];
1942         BOOL gotACommand = FALSE;
1943         BOOL handle_command_failed = FALSE;
1944         static U64 Poll_Count;
1945
1946         /* make sure visorbus server is registered for controlvm callbacks */
1947         if (visorchipset_serverregwait && !serverregistered)
1948                 goto Away;
1949         /* make sure visorclientbus server is regsitered for controlvm
1950          * callbacks
1951          */
1952         if (visorchipset_clientregwait && !clientregistered)
1953                 goto Away;
1954
1955         memset(&chanInfo, 0, sizeof(VISORCHIPSET_CHANNEL_INFO));
1956         if (!ControlVm_channel) {
1957                 HOSTADDRESS addr = controlvm_get_channel_address();
1958                 if (addr != 0) {
1959                         ControlVm_channel =
1960                             visorchannel_create_with_lock
1961                             (addr,
1962                              sizeof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL),
1963                              UltraControlvmChannelProtocolGuid);
1964                         if (ControlVm_channel == NULL)
1965                                 LOGERR("failed to create controlvm channel");
1966                         else if (ULTRA_CONTROLVM_CHANNEL_OK_CLIENT
1967                                  (visorchannel_get_header(ControlVm_channel),
1968                                   NULL)) {
1969                                 LOGINF("Channel %s (ControlVm) discovered",
1970                                        visorchannel_id(ControlVm_channel, s));
1971                                 initialize_controlvm_payload();
1972                         } else {
1973                                 LOGERR("controlvm channel is invalid");
1974                                 visorchannel_destroy(ControlVm_channel);
1975                                 ControlVm_channel = NULL;
1976                         }
1977                 }
1978         }
1979
1980         Poll_Count++;
1981         if ((ControlVm_channel != NULL) || (Poll_Count >= 250))
1982                 ;       /* keep going */
1983         else
1984                 goto Away;
1985
1986         /* Check events to determine if response to CHIPSET_READY
1987          * should be sent
1988          */
1989         if (visorchipset_holdchipsetready
1990             && (g_ChipSetMsgHdr.Id != CONTROLVM_INVALID)) {
1991                 if (check_chipset_events() == 1) {
1992                         LOGINF("Sending CHIPSET_READY response");
1993                         controlvm_respond(&g_ChipSetMsgHdr, 0);
1994                         clear_chipset_events();
1995                         memset(&g_ChipSetMsgHdr, 0,
1996                                sizeof(CONTROLVM_MESSAGE_HEADER));
1997                 }
1998         }
1999
2000         if (ControlVm_channel) {
2001                 while (visorchannel_signalremove(ControlVm_channel,
2002                                                  CONTROLVM_QUEUE_RESPONSE,
2003                                                  &inmsg)) {
2004                         if (inmsg.hdr.PayloadMaxBytes != 0) {
2005                                 LOGERR("Payload of size %lu returned @%lu with unexpected message id %d.",
2006                                      (ulong) inmsg.hdr.PayloadMaxBytes,
2007                                      (ulong) inmsg.hdr.PayloadVmOffset,
2008                                      inmsg.hdr.Id);
2009                         }
2010                 }
2011                 if (!gotACommand) {
2012                         if (ControlVm_Pending_Msg_Valid) {
2013                                 /* we throttled processing of a prior
2014                                 * msg, so try to process it again
2015                                 * rather than reading a new one
2016                                 */
2017                                 inmsg = ControlVm_Pending_Msg;
2018                                 ControlVm_Pending_Msg_Valid = FALSE;
2019                                 gotACommand = TRUE;
2020                         } else
2021                                 gotACommand = read_controlvm_event(&inmsg);
2022                 }
2023         }
2024
2025         handle_command_failed = FALSE;
2026         while (gotACommand && (!handle_command_failed)) {
2027                 Most_recent_message_jiffies = jiffies;
2028                 if (ControlVm_channel) {
2029                         if (handle_command(inmsg,
2030                                            visorchannel_get_physaddr
2031                                            (ControlVm_channel)))
2032                                 gotACommand = read_controlvm_event(&inmsg);
2033                         else {
2034                                 /* this is a scenario where throttling
2035                                 * is required, but probably NOT an
2036                                 * error...; we stash the current
2037                                 * controlvm msg so we will attempt to
2038                                 * reprocess it on our next loop
2039                                 */
2040                                 handle_command_failed = TRUE;
2041                                 ControlVm_Pending_Msg = inmsg;
2042                                 ControlVm_Pending_Msg_Valid = TRUE;
2043                         }
2044
2045                 } else {
2046                         handle_command(inmsg, 0);
2047                         gotACommand = FALSE;
2048                 }
2049         }
2050
2051         /* parahotplug_worker */
2052         parahotplug_process_list();
2053
2054 Away:
2055
2056         if (time_after(jiffies,
2057                        Most_recent_message_jiffies + (HZ * MIN_IDLE_SECONDS))) {
2058                 /* it's been longer than MIN_IDLE_SECONDS since we
2059                 * processed our last controlvm message; slow down the
2060                 * polling
2061                 */
2062                 if (Poll_jiffies != POLLJIFFIES_CONTROLVMCHANNEL_SLOW) {
2063                         LOGINF("switched to slow controlvm polling");
2064                         Poll_jiffies = POLLJIFFIES_CONTROLVMCHANNEL_SLOW;
2065                 }
2066         } else {
2067                 if (Poll_jiffies != POLLJIFFIES_CONTROLVMCHANNEL_FAST) {
2068                         Poll_jiffies = POLLJIFFIES_CONTROLVMCHANNEL_FAST;
2069                         LOGINF("switched to fast controlvm polling");
2070                 }
2071         }
2072
2073         queue_delayed_work(Periodic_controlvm_workqueue,
2074                            &Periodic_controlvm_work, Poll_jiffies);
2075 }
2076
2077 static void
2078 setup_crash_devices_work_queue(struct work_struct *work)
2079 {
2080
2081         CONTROLVM_MESSAGE localCrashCreateBusMsg;
2082         CONTROLVM_MESSAGE localCrashCreateDevMsg;
2083         CONTROLVM_MESSAGE msg;
2084         HOSTADDRESS host_addr;
2085         U32 localSavedCrashMsgOffset;
2086         U16 localSavedCrashMsgCount;
2087
2088         /* make sure visorbus server is registered for controlvm callbacks */
2089         if (visorchipset_serverregwait && !serverregistered)
2090                 goto Away;
2091
2092         /* make sure visorclientbus server is regsitered for controlvm
2093          * callbacks
2094          */
2095         if (visorchipset_clientregwait && !clientregistered)
2096                 goto Away;
2097
2098         POSTCODE_LINUX_2(CRASH_DEV_ENTRY_PC, POSTCODE_SEVERITY_INFO);
2099
2100         /* send init chipset msg */
2101         msg.hdr.Id = CONTROLVM_CHIPSET_INIT;
2102         msg.cmd.initChipset.busCount = 23;
2103         msg.cmd.initChipset.switchCount = 0;
2104
2105         chipset_init(&msg);
2106
2107         host_addr = controlvm_get_channel_address();
2108         if (!host_addr) {
2109                 LOGERR("Huh?  Host address is NULL");
2110                 POSTCODE_LINUX_2(CRASH_DEV_HADDR_NULL, POSTCODE_SEVERITY_ERR);
2111                 return;
2112         }
2113
2114         ControlVm_channel =
2115             visorchannel_create_with_lock
2116             (host_addr,
2117              sizeof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL),
2118              UltraControlvmChannelProtocolGuid);
2119
2120         if (ControlVm_channel == NULL) {
2121                 LOGERR("failed to create controlvm channel");
2122                 POSTCODE_LINUX_2(CRASH_DEV_CONTROLVM_NULL,
2123                                  POSTCODE_SEVERITY_ERR);
2124                 return;
2125         }
2126
2127         /* get saved message count */
2128         if (visorchannel_read(ControlVm_channel,
2129                               offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2130                                        SavedCrashMsgCount),
2131                               &localSavedCrashMsgCount, sizeof(U16)) < 0) {
2132                 LOGERR("failed to get Saved Message Count");
2133                 POSTCODE_LINUX_2(CRASH_DEV_CTRL_RD_FAILURE_PC,
2134                                  POSTCODE_SEVERITY_ERR);
2135                 return;
2136         }
2137
2138         if (localSavedCrashMsgCount != CONTROLVM_CRASHMSG_MAX) {
2139                 LOGERR("Saved Message Count incorrect %d",
2140                        localSavedCrashMsgCount);
2141                 POSTCODE_LINUX_3(CRASH_DEV_COUNT_FAILURE_PC,
2142                                  localSavedCrashMsgCount,
2143                                  POSTCODE_SEVERITY_ERR);
2144                 return;
2145         }
2146
2147         /* get saved crash message offset */
2148         if (visorchannel_read(ControlVm_channel,
2149                               offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2150                                        SavedCrashMsgOffset),
2151                               &localSavedCrashMsgOffset, sizeof(U32)) < 0) {
2152                 LOGERR("failed to get Saved Message Offset");
2153                 POSTCODE_LINUX_2(CRASH_DEV_CTRL_RD_FAILURE_PC,
2154                                  POSTCODE_SEVERITY_ERR);
2155                 return;
2156         }
2157
2158         /* read create device message for storage bus offset */
2159         if (visorchannel_read(ControlVm_channel,
2160                               localSavedCrashMsgOffset,
2161                               &localCrashCreateBusMsg,
2162                               sizeof(CONTROLVM_MESSAGE)) < 0) {
2163                 LOGERR("CRASH_DEV_RD_BUS_FAIULRE: Failed to read CrashCreateBusMsg!");
2164                 POSTCODE_LINUX_2(CRASH_DEV_RD_BUS_FAIULRE_PC,
2165                                  POSTCODE_SEVERITY_ERR);
2166                 return;
2167         }
2168
2169         /* read create device message for storage device */
2170         if (visorchannel_read(ControlVm_channel,
2171                               localSavedCrashMsgOffset +
2172                               sizeof(CONTROLVM_MESSAGE),
2173                               &localCrashCreateDevMsg,
2174                               sizeof(CONTROLVM_MESSAGE)) < 0) {
2175                 LOGERR("CRASH_DEV_RD_DEV_FAIULRE: Failed to read CrashCreateDevMsg!");
2176                 POSTCODE_LINUX_2(CRASH_DEV_RD_DEV_FAIULRE_PC,
2177                                  POSTCODE_SEVERITY_ERR);
2178                 return;
2179         }
2180
2181         /* reuse IOVM create bus message */
2182         if (localCrashCreateBusMsg.cmd.createBus.channelAddr != 0)
2183                 bus_create(&localCrashCreateBusMsg);
2184         else {
2185                 LOGERR("CrashCreateBusMsg is null, no dump will be taken");
2186                 POSTCODE_LINUX_2(CRASH_DEV_BUS_NULL_FAILURE_PC,
2187                                  POSTCODE_SEVERITY_ERR);
2188                 return;
2189         }
2190
2191         /* reuse create device message for storage device */
2192         if (localCrashCreateDevMsg.cmd.createDevice.channelAddr != 0)
2193                 my_device_create(&localCrashCreateDevMsg);
2194         else {
2195                 LOGERR("CrashCreateDevMsg is null, no dump will be taken");
2196                 POSTCODE_LINUX_2(CRASH_DEV_DEV_NULL_FAILURE_PC,
2197                                  POSTCODE_SEVERITY_ERR);
2198                 return;
2199         }
2200         LOGINF("Bus and device ready for dumping");
2201         POSTCODE_LINUX_2(CRASH_DEV_EXIT_PC, POSTCODE_SEVERITY_INFO);
2202         return;
2203
2204 Away:
2205
2206         Poll_jiffies = POLLJIFFIES_CONTROLVMCHANNEL_SLOW;
2207
2208         queue_delayed_work(Periodic_controlvm_workqueue,
2209                            &Periodic_controlvm_work, Poll_jiffies);
2210 }
2211
2212 static void
2213 bus_create_response(ulong busNo, int response)
2214 {
2215         bus_responder(CONTROLVM_BUS_CREATE, busNo, response);
2216 }
2217
2218 static void
2219 bus_destroy_response(ulong busNo, int response)
2220 {
2221         bus_responder(CONTROLVM_BUS_DESTROY, busNo, response);
2222 }
2223
2224 static void
2225 device_create_response(ulong busNo, ulong devNo, int response)
2226 {
2227         device_responder(CONTROLVM_DEVICE_CREATE, busNo, devNo, response);
2228 }
2229
2230 static void
2231 device_destroy_response(ulong busNo, ulong devNo, int response)
2232 {
2233         device_responder(CONTROLVM_DEVICE_DESTROY, busNo, devNo, response);
2234 }
2235
2236 void
2237 visorchipset_device_pause_response(ulong busNo, ulong devNo, int response)
2238 {
2239
2240         device_changestate_responder(CONTROLVM_DEVICE_CHANGESTATE,
2241                                      busNo, devNo, response,
2242                                      SegmentStateStandby);
2243 }
2244 EXPORT_SYMBOL_GPL(visorchipset_device_pause_response);
2245
2246 static void
2247 device_resume_response(ulong busNo, ulong devNo, int response)
2248 {
2249         device_changestate_responder(CONTROLVM_DEVICE_CHANGESTATE,
2250                                      busNo, devNo, response,
2251                                      SegmentStateRunning);
2252 }
2253
2254 BOOL
2255 visorchipset_get_bus_info(ulong busNo, VISORCHIPSET_BUS_INFO *busInfo)
2256 {
2257         void *p = findbus(&BusInfoList, busNo);
2258         if (!p) {
2259                 LOGERR("(%lu) failed", busNo);
2260                 return FALSE;
2261         }
2262         memcpy(busInfo, p, sizeof(VISORCHIPSET_BUS_INFO));
2263         return TRUE;
2264 }
2265 EXPORT_SYMBOL_GPL(visorchipset_get_bus_info);
2266
2267 BOOL
2268 visorchipset_set_bus_context(ulong busNo, void *context)
2269 {
2270         VISORCHIPSET_BUS_INFO *p = findbus(&BusInfoList, busNo);
2271         if (!p) {
2272                 LOGERR("(%lu) failed", busNo);
2273                 return FALSE;
2274         }
2275         p->bus_driver_context = context;
2276         return TRUE;
2277 }
2278 EXPORT_SYMBOL_GPL(visorchipset_set_bus_context);
2279
2280 BOOL
2281 visorchipset_get_device_info(ulong busNo, ulong devNo,
2282                              VISORCHIPSET_DEVICE_INFO *devInfo)
2283 {
2284         void *p = finddevice(&DevInfoList, busNo, devNo);
2285         if (!p) {
2286                 LOGERR("(%lu,%lu) failed", busNo, devNo);
2287                 return FALSE;
2288         }
2289         memcpy(devInfo, p, sizeof(VISORCHIPSET_DEVICE_INFO));
2290         return TRUE;
2291 }
2292 EXPORT_SYMBOL_GPL(visorchipset_get_device_info);
2293
2294 BOOL
2295 visorchipset_set_device_context(ulong busNo, ulong devNo, void *context)
2296 {
2297         VISORCHIPSET_DEVICE_INFO *p = finddevice(&DevInfoList, busNo, devNo);
2298         if (!p) {
2299                 LOGERR("(%lu,%lu) failed", busNo, devNo);
2300                 return FALSE;
2301         }
2302         p->bus_driver_context = context;
2303         return TRUE;
2304 }
2305 EXPORT_SYMBOL_GPL(visorchipset_set_device_context);
2306
2307 /* Generic wrapper function for allocating memory from a kmem_cache pool.
2308  */
2309 void *
2310 visorchipset_cache_alloc(struct kmem_cache *pool, BOOL ok_to_block,
2311                          char *fn, int ln)
2312 {
2313         gfp_t gfp;
2314         void *p;
2315
2316         if (ok_to_block)
2317                 gfp = GFP_KERNEL;
2318         else
2319                 gfp = GFP_ATOMIC;
2320         /* __GFP_NORETRY means "ok to fail", meaning
2321          * kmem_cache_alloc() can return NULL, implying the caller CAN
2322          * cope with failure.  If you do NOT specify __GFP_NORETRY,
2323          * Linux will go to extreme measures to get memory for you
2324          * (like, invoke oom killer), which will probably cripple the
2325          * system.
2326          */
2327         gfp |= __GFP_NORETRY;
2328         p = kmem_cache_alloc(pool, gfp);
2329         if (!p) {
2330                 LOGERR("kmem_cache_alloc failed early @%s:%d\n", fn, ln);
2331                 return NULL;
2332         }
2333         atomic_inc(&Visorchipset_cache_buffers_in_use);
2334         return p;
2335 }
2336
2337 /* Generic wrapper function for freeing memory from a kmem_cache pool.
2338  */
2339 void
2340 visorchipset_cache_free(struct kmem_cache *pool, void *p, char *fn, int ln)
2341 {
2342         if (!p) {
2343                 LOGERR("NULL pointer @%s:%d\n", fn, ln);
2344                 return;
2345         }
2346         atomic_dec(&Visorchipset_cache_buffers_in_use);
2347         kmem_cache_free(pool, p);
2348 }
2349
2350 #define gettoken(bufp) strsep(bufp, " -\t\n")
2351
2352 static ssize_t
2353 chipset_proc_write(struct file *file, const char __user *buffer,
2354                    size_t count, loff_t *ppos)
2355 {
2356         char buf[512];
2357         char *token, *p;
2358
2359         if (count > sizeof(buf) - 1) {
2360                 LOGERR("chipset_proc_write: count (%d) exceeds size of buffer (%d)",
2361                      (int) count, (int) sizeof(buffer));
2362                 return -EINVAL;
2363         }
2364         if (copy_from_user(buf, buffer, count)) {
2365                 LOGERR("chipset_proc_write: copy_from_user failed");
2366                 return -EFAULT;
2367         }
2368         buf[count] = '\0';
2369
2370         p = buf;
2371         token = gettoken(&p);
2372
2373         if (strcmp(token, "CALLHOMEDISK_MOUNTED") == 0) {
2374                 token = gettoken(&p);
2375                 /* The Call Home Disk has been mounted */
2376                 if (strcmp(token, "0") == 0)
2377                         chipset_events[0] = 1;
2378         } else if (strcmp(token, "MODULES_LOADED") == 0) {
2379                 token = gettoken(&p);
2380                 /* All modules for the partition have been loaded */
2381                 if (strcmp(token, "0") == 0)
2382                         chipset_events[1] = 1;
2383         } else if (token == NULL) {
2384                 /* No event specified */
2385                 LOGERR("No event was specified to send CHIPSET_READY response");
2386                 return -1;
2387         } else {
2388                 /* Unsupported event specified */
2389                 LOGERR("%s is an invalid event for sending CHIPSET_READY response",                  token);
2390                 return -1;
2391         }
2392
2393         return count;
2394 }
2395
2396 static ssize_t
2397 visorchipset_proc_read_writeonly(struct file *file, char __user *buf,
2398                                  size_t len, loff_t *offset)
2399 {
2400         return 0;
2401 }
2402
2403 /**
2404  * Reads the InstallationError, InstallationTextId,
2405  * InstallationRemainingSteps fields of ControlVMChannel.
2406  */
2407 static ssize_t
2408 proc_read_installer(struct file *file, char __user *buf,
2409                     size_t len, loff_t *offset)
2410 {
2411         int length = 0;
2412         U16 remainingSteps;
2413         U32 error, textId;
2414         char *vbuf;
2415         loff_t pos = *offset;
2416
2417         if (!ControlVm_channel)
2418                 return -ENODEV;
2419
2420         if (pos < 0)
2421                 return -EINVAL;
2422
2423         if (pos > 0 || !len)
2424                 return 0;
2425
2426         vbuf = kzalloc(len, GFP_KERNEL);
2427         if (!vbuf)
2428                 return -ENOMEM;
2429
2430         visorchannel_read(ControlVm_channel,
2431                           offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2432                                    InstallationRemainingSteps), &remainingSteps,
2433                           sizeof(U16));
2434         visorchannel_read(ControlVm_channel,
2435                           offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2436                                    InstallationError), &error, sizeof(U32));
2437         visorchannel_read(ControlVm_channel,
2438                           offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2439                                    InstallationTextId), &textId, sizeof(U32));
2440
2441         length = sprintf(vbuf, "%u %u %u\n", remainingSteps, error, textId);
2442         if (copy_to_user(buf, vbuf, length)) {
2443                 kfree(vbuf);
2444                 return -EFAULT;
2445         }
2446
2447         kfree(vbuf);
2448         *offset += length;
2449         return length;
2450 }
2451
2452 /**
2453  * Writes to the InstallationError, InstallationTextId,
2454  * InstallationRemainingSteps fields of
2455  * ControlVMChannel.
2456  * Input: RemainingSteps Error TextId
2457  * Limit 32 characters input
2458  */
2459 #define UINT16_MAX              (65535U)
2460 #define UINT32_MAX              (4294967295U)
2461 static ssize_t
2462 proc_write_installer(struct file *file,
2463                      const char __user *buffer, size_t count, loff_t *ppos)
2464 {
2465         char buf[32];
2466         U16 remainingSteps;
2467         U32 error, textId;
2468
2469         if (!ControlVm_channel)
2470                 return -ENODEV;
2471
2472         /* Check to make sure there is no buffer overflow */
2473         if (count > (sizeof(buf) - 1))
2474                 return -EINVAL;
2475
2476         if (copy_from_user(buf, buffer, count)) {
2477                 WARN(1, "Error copying from user space\n");
2478                 return -EFAULT;
2479         }
2480
2481         if (sscanf(buf, "%hu %i %i", &remainingSteps, &error, &textId) != 3) {
2482                 remainingSteps = UINT16_MAX;
2483                 error = UINT32_MAX;
2484                 textId = UINT32_MAX;
2485         }
2486
2487         if (remainingSteps != UINT16_MAX) {
2488                 if (visorchannel_write
2489                     (ControlVm_channel,
2490                      offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2491                               InstallationRemainingSteps), &remainingSteps,
2492                      sizeof(U16)) < 0)
2493                         WARN(1, "Installation Status Write Failed - Write function error - RemainingSteps = %d\n",
2494                              remainingSteps);
2495         }
2496
2497         if (error != UINT32_MAX) {
2498                 if (visorchannel_write
2499                     (ControlVm_channel,
2500                      offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2501                               InstallationError), &error, sizeof(U32)) < 0)
2502                         WARN(1, "Installation Status Write Failed - Write function error - Error = %d\n",
2503                              error);
2504         }
2505
2506         if (textId != UINT32_MAX) {
2507                 if (visorchannel_write
2508                     (ControlVm_channel,
2509                      offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2510                               InstallationTextId), &textId, sizeof(U32)) < 0)
2511                         WARN(1, "Installation Status Write Failed - Write function error - TextId = %d\n",
2512                              textId);
2513         }
2514
2515         /* So this function isn't called multiple times, must return
2516          * size of buffer
2517          */
2518         return count;
2519 }
2520
2521 /**
2522  * Reads the ToolAction field of ControlVMChannel.
2523  */
2524 static ssize_t
2525 proc_read_toolaction(struct file *file, char __user *buf,
2526                      size_t len, loff_t *offset)
2527 {
2528         int length = 0;
2529         U8 toolAction;
2530         char *vbuf;
2531         loff_t pos = *offset;
2532
2533         if (!ControlVm_channel)
2534                 return -ENODEV;
2535
2536         if (pos < 0)
2537                 return -EINVAL;
2538
2539         if (pos > 0 || !len)
2540                 return 0;
2541
2542         vbuf = kzalloc(len, GFP_KERNEL);
2543         if (!vbuf)
2544                 return -ENOMEM;
2545
2546         visorchannel_read(ControlVm_channel,
2547                           offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2548                                    ToolAction), &toolAction, sizeof(U8));
2549
2550         length = sprintf(vbuf, "%u\n", toolAction);
2551         if (copy_to_user(buf, vbuf, length)) {
2552                 kfree(vbuf);
2553                 return -EFAULT;
2554         }
2555
2556         kfree(vbuf);
2557         *offset += length;
2558         return length;
2559 }
2560
2561 /**
2562  * Writes to the ToolAction field of ControlVMChannel.
2563  * Input: ToolAction
2564  * Limit 3 characters input
2565  */
2566 #define UINT8_MAX (255U)
2567 static ssize_t
2568 proc_write_toolaction(struct file *file,
2569                       const char __user *buffer, size_t count, loff_t *ppos)
2570 {
2571         char buf[3];
2572         U8 toolAction;
2573
2574         if (!ControlVm_channel)
2575                 return -ENODEV;
2576
2577         /* Check to make sure there is no buffer overflow */
2578         if (count > (sizeof(buf) - 1))
2579                 return -EINVAL;
2580
2581         if (copy_from_user(buf, buffer, count)) {
2582                 WARN(1, "Error copying from user space\n");
2583                 return -EFAULT;
2584         }
2585
2586         if (sscanf(buf, "%hhd", &toolAction) != 1)
2587                 toolAction = UINT8_MAX;
2588
2589         if (toolAction != UINT8_MAX) {
2590                 if (visorchannel_write
2591                     (ControlVm_channel,
2592                      offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL, ToolAction),
2593                      &toolAction, sizeof(U8)) < 0)
2594                         WARN(1, "Installation ToolAction Write Failed - ToolAction = %d\n",
2595                              toolAction);
2596         }
2597
2598         /* So this function isn't called multiple times, must return
2599          * size of buffer
2600          */
2601         return count;
2602 }
2603
2604 /**
2605  * Reads the EfiSparIndication.BootToTool field of ControlVMChannel.
2606  */
2607 static ssize_t
2608 proc_read_bootToTool(struct file *file, char __user *buf,
2609                      size_t len, loff_t *offset)
2610 {
2611         int length = 0;
2612         ULTRA_EFI_SPAR_INDICATION efiSparIndication;
2613         char *vbuf;
2614         loff_t pos = *offset;
2615
2616         if (!ControlVm_channel)
2617                 return -ENODEV;
2618
2619         if (pos < 0)
2620                 return -EINVAL;
2621
2622         if (pos > 0 || !len)
2623                 return 0;
2624
2625         vbuf = kzalloc(len, GFP_KERNEL);
2626         if (!vbuf)
2627                 return -ENOMEM;
2628
2629         visorchannel_read(ControlVm_channel,
2630                           offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL,
2631                                    EfiSparIndication), &efiSparIndication,
2632                           sizeof(ULTRA_EFI_SPAR_INDICATION));
2633
2634         length = sprintf(vbuf, "%d\n", (int) efiSparIndication.BootToTool);
2635         if (copy_to_user(buf, vbuf, length)) {
2636                 kfree(vbuf);
2637                 return -EFAULT;
2638         }
2639
2640         kfree(vbuf);
2641         *offset += length;
2642         return length;
2643 }
2644
2645 /**
2646  * Writes to the EfiSparIndication.BootToTool field of ControlVMChannel.
2647  * Input: 1 or 0 (1 being on, 0 being off)
2648  */
2649 static ssize_t
2650 proc_write_bootToTool(struct file *file,
2651                       const char __user *buffer, size_t count, loff_t *ppos)
2652 {
2653         char buf[3];
2654         int inputVal;
2655         ULTRA_EFI_SPAR_INDICATION efiSparIndication;
2656
2657         if (!ControlVm_channel)
2658                 return -ENODEV;
2659
2660         /* Check to make sure there is no buffer overflow */
2661         if (count > (sizeof(buf) - 1))
2662                 return -EINVAL;
2663
2664         if (copy_from_user(buf, buffer, count)) {
2665                 WARN(1, "Error copying from user space\n");
2666                 return -EFAULT;
2667         }
2668
2669         if (sscanf(buf, "%i", &inputVal) != 1)
2670                 inputVal = 0;
2671
2672         efiSparIndication.BootToTool = (inputVal == 1 ? 1 : 0);
2673
2674         if (visorchannel_write
2675             (ControlVm_channel,
2676              offsetof(ULTRA_CONTROLVM_CHANNEL_PROTOCOL, EfiSparIndication),
2677              &efiSparIndication, sizeof(ULTRA_EFI_SPAR_INDICATION)) < 0)
2678                 printk
2679                     ("Installation BootToTool Write Failed - BootToTool = %d\n",
2680                      (int) efiSparIndication.BootToTool);
2681
2682         /* So this function isn't called multiple times, must return
2683          * size of buffer
2684          */
2685         return count;
2686 }
2687
2688 static const struct file_operations chipset_proc_fops = {
2689         .owner = THIS_MODULE,
2690         .read = visorchipset_proc_read_writeonly,
2691         .write = chipset_proc_write,
2692 };
2693
2694 static int __init
2695 visorchipset_init(void)
2696 {
2697         int rc = 0, x = 0;
2698         struct proc_dir_entry *installer_file;
2699         struct proc_dir_entry *toolaction_file;
2700         struct proc_dir_entry *bootToTool_file;
2701
2702         LOGINF("chipset driver version %s loaded", VERSION);
2703         /* process module options */
2704         POSTCODE_LINUX_2(DRIVER_ENTRY_PC, POSTCODE_SEVERITY_INFO);
2705
2706         LOGINF("option - testvnic=%d", visorchipset_testvnic);
2707         LOGINF("option - testvnicclient=%d", visorchipset_testvnicclient);
2708         LOGINF("option - testmsg=%d", visorchipset_testmsg);
2709         LOGINF("option - testteardown=%d", visorchipset_testteardown);
2710         LOGINF("option - major=%d", visorchipset_major);
2711         LOGINF("option - serverregwait=%d", visorchipset_serverregwait);
2712         LOGINF("option - clientregwait=%d", visorchipset_clientregwait);
2713         LOGINF("option - holdchipsetready=%d", visorchipset_holdchipsetready);
2714
2715         memset(&BusDev_Server_Notifiers, 0, sizeof(BusDev_Server_Notifiers));
2716         memset(&BusDev_Client_Notifiers, 0, sizeof(BusDev_Client_Notifiers));
2717         memset(&ControlVm_payload_info, 0, sizeof(ControlVm_payload_info));
2718         memset(&LiveDump_info, 0, sizeof(LiveDump_info));
2719         atomic_set(&LiveDump_info.buffers_in_use, 0);
2720
2721         if (visorchipset_testvnic) {
2722                 ERRDRV("testvnic option no longer supported: (status = %d)\n",
2723                        x);
2724                 POSTCODE_LINUX_3(CHIPSET_INIT_FAILURE_PC, x, DIAG_SEVERITY_ERR);
2725                 rc = x;
2726                 goto Away;
2727         }
2728
2729         controlvm_init();
2730         MajorDev = MKDEV(visorchipset_major, 0);
2731         rc = visorchipset_file_init(MajorDev, &ControlVm_channel);
2732         if (rc < 0) {
2733                 ERRDRV("visorchipset_file_init(MajorDev, &ControlVm_channel): error (status=%d)\n", rc);
2734                 POSTCODE_LINUX_2(CHIPSET_INIT_FAILURE_PC, DIAG_SEVERITY_ERR);
2735                 goto Away;
2736         }
2737
2738         proc_Init();
2739         memset(PartitionPropertyNames, 0, sizeof(PartitionPropertyNames));
2740         memset(ControlVmPropertyNames, 0, sizeof(ControlVmPropertyNames));
2741         InitPartitionProperties();
2742         InitControlVmProperties();
2743
2744         PartitionType = visor_proc_CreateType(ProcDir, PartitionTypeNames,
2745                                               (const char **)
2746                                               PartitionPropertyNames,
2747                                               &show_partition_property);
2748         ControlVmType =
2749             visor_proc_CreateType(ProcDir, ControlVmTypeNames,
2750                                   (const char **) ControlVmPropertyNames,
2751                                   &show_controlvm_property);
2752
2753         ControlVmObject = visor_proc_CreateObject(ControlVmType, NULL, NULL);
2754
2755         /* Setup Installation fields */
2756         installer_file = proc_create("installer", 0644, ProcDir,
2757                                      &proc_installer_fops);
2758         /* Setup the ToolAction field */
2759         toolaction_file = proc_create("toolaction", 0644, ProcDir,
2760                                       &proc_toolaction_fops);
2761         /* Setup the BootToTool field */
2762         bootToTool_file = proc_create("boottotool", 0644, ProcDir,
2763                                       &proc_bootToTool_fops);
2764
2765         memset(&g_DiagMsgHdr, 0, sizeof(CONTROLVM_MESSAGE_HEADER));
2766
2767         chipset_proc_dir = proc_create(VISORCHIPSET_CHIPSET_PROC_ENTRY_FN,
2768                                        0644, ProcDir, &chipset_proc_fops);
2769         memset(&g_ChipSetMsgHdr, 0, sizeof(CONTROLVM_MESSAGE_HEADER));
2770
2771         parahotplug_proc_dir =
2772             proc_create(VISORCHIPSET_PARAHOTPLUG_PROC_ENTRY_FN, 0200,
2773                         ProcDir, &parahotplug_proc_fops);
2774         memset(&g_DelDumpMsgHdr, 0, sizeof(CONTROLVM_MESSAGE_HEADER));
2775
2776         if (filexfer_constructor(sizeof(struct putfile_request)) < 0) {
2777                 ERRDRV("filexfer_constructor failed: (status=-1)\n");
2778                 POSTCODE_LINUX_2(CHIPSET_INIT_FAILURE_PC, DIAG_SEVERITY_ERR);
2779                 rc = -1;
2780                 goto Away;
2781         }
2782         Putfile_buffer_list_pool =
2783             kmem_cache_create(Putfile_buffer_list_pool_name,
2784                               sizeof(struct putfile_buffer_entry),
2785                               0, SLAB_HWCACHE_ALIGN, NULL);
2786         if (!Putfile_buffer_list_pool) {
2787                 ERRDRV("failed to alloc Putfile_buffer_list_pool: (status=-1)\n");
2788                 POSTCODE_LINUX_2(CHIPSET_INIT_FAILURE_PC, DIAG_SEVERITY_ERR);
2789                 rc = -1;
2790                 goto Away;
2791         }
2792         if (visorchipset_disable_controlvm) {
2793                 LOGINF("visorchipset_init:controlvm disabled");
2794         } else {
2795                 /* if booting in a crash kernel */
2796                 if (visorchipset_crash_kernel)
2797                         INIT_DELAYED_WORK(&Periodic_controlvm_work,
2798                                           setup_crash_devices_work_queue);
2799                 else
2800                         INIT_DELAYED_WORK(&Periodic_controlvm_work,
2801                                           controlvm_periodic_work);
2802                 Periodic_controlvm_workqueue =
2803                     create_singlethread_workqueue("visorchipset_controlvm");
2804
2805                 if (Periodic_controlvm_workqueue == NULL) {
2806                         ERRDRV("cannot create controlvm workqueue: (status=%d)\n",
2807                                -ENOMEM);
2808                         POSTCODE_LINUX_2(CREATE_WORKQUEUE_FAILED_PC,
2809                                          DIAG_SEVERITY_ERR);
2810                         rc = -ENOMEM;
2811                         goto Away;
2812                 }
2813                 Most_recent_message_jiffies = jiffies;
2814                 Poll_jiffies = POLLJIFFIES_CONTROLVMCHANNEL_FAST;
2815                 rc = queue_delayed_work(Periodic_controlvm_workqueue,
2816                                         &Periodic_controlvm_work, Poll_jiffies);
2817                 if (rc < 0) {
2818                         ERRDRV("queue_delayed_work(Periodic_controlvm_workqueue, &Periodic_controlvm_work, Poll_jiffies): error (status=%d)\n", rc);
2819                         POSTCODE_LINUX_2(QUEUE_DELAYED_WORK_PC,
2820                                          DIAG_SEVERITY_ERR);
2821                         goto Away;
2822                 }
2823
2824         }
2825
2826         Visorchipset_platform_device.dev.devt = MajorDev;
2827         if (platform_device_register(&Visorchipset_platform_device) < 0) {
2828                 ERRDRV("platform_device_register(visorchipset) failed: (status=-1)\n");
2829                 POSTCODE_LINUX_2(DEVICE_REGISTER_FAILURE_PC, DIAG_SEVERITY_ERR);
2830                 rc = -1;
2831                 goto Away;
2832         }
2833         LOGINF("visorchipset device created");
2834         POSTCODE_LINUX_2(CHIPSET_INIT_SUCCESS_PC, POSTCODE_SEVERITY_INFO);
2835         rc = 0;
2836 Away:
2837         if (rc) {
2838                 LOGERR("visorchipset_init failed");
2839                 POSTCODE_LINUX_3(CHIPSET_INIT_FAILURE_PC, rc,
2840                                  POSTCODE_SEVERITY_ERR);
2841         }
2842         return rc;
2843 }
2844
2845 static void
2846 visorchipset_exit(void)
2847 {
2848         char s[99];
2849         POSTCODE_LINUX_2(DRIVER_EXIT_PC, POSTCODE_SEVERITY_INFO);
2850
2851         if (visorchipset_disable_controlvm) {
2852                 ;
2853         } else {
2854                 cancel_delayed_work(&Periodic_controlvm_work);
2855                 flush_workqueue(Periodic_controlvm_workqueue);
2856                 destroy_workqueue(Periodic_controlvm_workqueue);
2857                 Periodic_controlvm_workqueue = NULL;
2858                 destroy_controlvm_payload_info(&ControlVm_payload_info);
2859         }
2860         Test_Vnic_channel = NULL;
2861         if (Putfile_buffer_list_pool) {
2862                 kmem_cache_destroy(Putfile_buffer_list_pool);
2863                 Putfile_buffer_list_pool = NULL;
2864         }
2865         filexfer_destructor();
2866         if (ControlVmObject) {
2867                 visor_proc_DestroyObject(ControlVmObject);
2868                 ControlVmObject = NULL;
2869         }
2870         cleanup_controlvm_structures();
2871
2872         if (ControlVmType) {
2873                 visor_proc_DestroyType(ControlVmType);
2874                 ControlVmType = NULL;
2875         }
2876         if (PartitionType) {
2877                 visor_proc_DestroyType(PartitionType);
2878                 PartitionType = NULL;
2879         }
2880         if (diag_proc_dir) {
2881                 remove_proc_entry(VISORCHIPSET_DIAG_PROC_ENTRY_FN, ProcDir);
2882                 diag_proc_dir = NULL;
2883         }
2884         memset(&g_DiagMsgHdr, 0, sizeof(CONTROLVM_MESSAGE_HEADER));
2885
2886         if (chipset_proc_dir) {
2887                 remove_proc_entry(VISORCHIPSET_CHIPSET_PROC_ENTRY_FN, ProcDir);
2888                 chipset_proc_dir = NULL;
2889         }
2890         memset(&g_ChipSetMsgHdr, 0, sizeof(CONTROLVM_MESSAGE_HEADER));
2891
2892         if (parahotplug_proc_dir) {
2893                 remove_proc_entry(VISORCHIPSET_PARAHOTPLUG_PROC_ENTRY_FN,
2894                                   ProcDir);
2895                 parahotplug_proc_dir = NULL;
2896         }
2897
2898         memset(&g_DelDumpMsgHdr, 0, sizeof(CONTROLVM_MESSAGE_HEADER));
2899
2900         proc_DeInit();
2901         if (ControlVm_channel != NULL) {
2902                 LOGINF("Channel %s (ControlVm) disconnected",
2903                        visorchannel_id(ControlVm_channel, s));
2904                 visorchannel_destroy(ControlVm_channel);
2905                 ControlVm_channel = NULL;
2906         }
2907         controlvm_deinit();
2908         visorchipset_file_cleanup();
2909         POSTCODE_LINUX_2(DRIVER_EXIT_PC, POSTCODE_SEVERITY_INFO);
2910         LOGINF("chipset driver unloaded");
2911 }
2912
2913 module_param_named(testvnic, visorchipset_testvnic, int, S_IRUGO);
2914 MODULE_PARM_DESC(visorchipset_testvnic, "1 to test vnic, using dummy VNIC connected via a loopback to a physical ethernet");
2915 int visorchipset_testvnic = 0;
2916
2917 module_param_named(testvnicclient, visorchipset_testvnicclient, int, S_IRUGO);
2918 MODULE_PARM_DESC(visorchipset_testvnicclient, "1 to test vnic, using real VNIC channel attached to a separate IOVM guest");
2919 int visorchipset_testvnicclient = 0;
2920
2921 module_param_named(testmsg, visorchipset_testmsg, int, S_IRUGO);
2922 MODULE_PARM_DESC(visorchipset_testmsg,
2923                  "1 to manufacture the chipset, bus, and switch messages");
2924 int visorchipset_testmsg = 0;
2925
2926 module_param_named(major, visorchipset_major, int, S_IRUGO);
2927 MODULE_PARM_DESC(visorchipset_major, "major device number to use for the device node");
2928 int visorchipset_major = 0;
2929
2930 module_param_named(serverregwait, visorchipset_serverregwait, int, S_IRUGO);
2931 MODULE_PARM_DESC(visorchipset_serverreqwait,
2932                  "1 to have the module wait for the visor bus to register");
2933 int visorchipset_serverregwait = 0;     /* default is off */
2934 module_param_named(clientregwait, visorchipset_clientregwait, int, S_IRUGO);
2935 MODULE_PARM_DESC(visorchipset_clientregwait, "1 to have the module wait for the visorclientbus to register");
2936 int visorchipset_clientregwait = 1;     /* default is on */
2937 module_param_named(testteardown, visorchipset_testteardown, int, S_IRUGO);
2938 MODULE_PARM_DESC(visorchipset_testteardown,
2939                  "1 to test teardown of the chipset, bus, and switch");
2940 int visorchipset_testteardown = 0;      /* default is off */
2941 module_param_named(disable_controlvm, visorchipset_disable_controlvm, int,
2942                    S_IRUGO);
2943 MODULE_PARM_DESC(visorchipset_disable_controlvm,
2944                  "1 to disable polling of controlVm channel");
2945 int visorchipset_disable_controlvm = 0; /* default is off */
2946 module_param_named(crash_kernel, visorchipset_crash_kernel, int, S_IRUGO);
2947 MODULE_PARM_DESC(visorchipset_crash_kernel,
2948                  "1 means we are running in crash kernel");
2949 int visorchipset_crash_kernel = 0; /* default is running in non-crash kernel */
2950 module_param_named(holdchipsetready, visorchipset_holdchipsetready,
2951                    int, S_IRUGO);
2952 MODULE_PARM_DESC(visorchipset_holdchipsetready,
2953                  "1 to hold response to CHIPSET_READY");
2954 int visorchipset_holdchipsetready = 0; /* default is to send CHIPSET_READY
2955                                       * response immediately */
2956 module_init(visorchipset_init);
2957 module_exit(visorchipset_exit);
2958
2959 MODULE_AUTHOR("Unisys");
2960 MODULE_LICENSE("GPL");
2961 MODULE_DESCRIPTION("Supervisor chipset driver for service partition: ver "
2962                    VERSION);
2963 MODULE_VERSION(VERSION);