xref: /openbmc/qemu/hw/s390x/css.c (revision 10df8ff1)
1 /*
2  * Channel subsystem base support.
3  *
4  * Copyright 2012 IBM Corp.
5  * Author(s): Cornelia Huck <cornelia.huck@de.ibm.com>
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or (at
8  * your option) any later version. See the COPYING file in the top-level
9  * directory.
10  */
11 
12 #include "qemu/osdep.h"
13 #include "qapi/error.h"
14 #include "qapi/visitor.h"
15 #include "hw/qdev.h"
16 #include "qemu/bitops.h"
17 #include "qemu/error-report.h"
18 #include "exec/address-spaces.h"
19 #include "cpu.h"
20 #include "hw/s390x/ioinst.h"
21 #include "hw/s390x/css.h"
22 #include "trace.h"
23 #include "hw/s390x/s390_flic.h"
24 #include "hw/s390x/s390-virtio-ccw.h"
25 
26 typedef struct CrwContainer {
27     CRW crw;
28     QTAILQ_ENTRY(CrwContainer) sibling;
29 } CrwContainer;
30 
31 static const VMStateDescription vmstate_crw = {
32     .name = "s390_crw",
33     .version_id = 1,
34     .minimum_version_id = 1,
35     .fields = (VMStateField[]) {
36         VMSTATE_UINT16(flags, CRW),
37         VMSTATE_UINT16(rsid, CRW),
38         VMSTATE_END_OF_LIST()
39     },
40 };
41 
42 static const VMStateDescription vmstate_crw_container = {
43     .name = "s390_crw_container",
44     .version_id = 1,
45     .minimum_version_id = 1,
46     .fields = (VMStateField[]) {
47         VMSTATE_STRUCT(crw, CrwContainer, 0, vmstate_crw, CRW),
48         VMSTATE_END_OF_LIST()
49     },
50 };
51 
52 typedef struct ChpInfo {
53     uint8_t in_use;
54     uint8_t type;
55     uint8_t is_virtual;
56 } ChpInfo;
57 
58 static const VMStateDescription vmstate_chp_info = {
59     .name = "s390_chp_info",
60     .version_id = 1,
61     .minimum_version_id = 1,
62     .fields = (VMStateField[]) {
63         VMSTATE_UINT8(in_use, ChpInfo),
64         VMSTATE_UINT8(type, ChpInfo),
65         VMSTATE_UINT8(is_virtual, ChpInfo),
66         VMSTATE_END_OF_LIST()
67     }
68 };
69 
70 typedef struct SubchSet {
71     SubchDev *sch[MAX_SCHID + 1];
72     unsigned long schids_used[BITS_TO_LONGS(MAX_SCHID + 1)];
73     unsigned long devnos_used[BITS_TO_LONGS(MAX_SCHID + 1)];
74 } SubchSet;
75 
76 static const VMStateDescription vmstate_scsw = {
77     .name = "s390_scsw",
78     .version_id = 1,
79     .minimum_version_id = 1,
80     .fields = (VMStateField[]) {
81         VMSTATE_UINT16(flags, SCSW),
82         VMSTATE_UINT16(ctrl, SCSW),
83         VMSTATE_UINT32(cpa, SCSW),
84         VMSTATE_UINT8(dstat, SCSW),
85         VMSTATE_UINT8(cstat, SCSW),
86         VMSTATE_UINT16(count, SCSW),
87         VMSTATE_END_OF_LIST()
88     }
89 };
90 
91 static const VMStateDescription vmstate_pmcw = {
92     .name = "s390_pmcw",
93     .version_id = 1,
94     .minimum_version_id = 1,
95     .fields = (VMStateField[]) {
96         VMSTATE_UINT32(intparm, PMCW),
97         VMSTATE_UINT16(flags, PMCW),
98         VMSTATE_UINT16(devno, PMCW),
99         VMSTATE_UINT8(lpm, PMCW),
100         VMSTATE_UINT8(pnom, PMCW),
101         VMSTATE_UINT8(lpum, PMCW),
102         VMSTATE_UINT8(pim, PMCW),
103         VMSTATE_UINT16(mbi, PMCW),
104         VMSTATE_UINT8(pom, PMCW),
105         VMSTATE_UINT8(pam, PMCW),
106         VMSTATE_UINT8_ARRAY(chpid, PMCW, 8),
107         VMSTATE_UINT32(chars, PMCW),
108         VMSTATE_END_OF_LIST()
109     }
110 };
111 
112 static const VMStateDescription vmstate_schib = {
113     .name = "s390_schib",
114     .version_id = 1,
115     .minimum_version_id = 1,
116     .fields = (VMStateField[]) {
117         VMSTATE_STRUCT(pmcw, SCHIB, 0, vmstate_pmcw, PMCW),
118         VMSTATE_STRUCT(scsw, SCHIB, 0, vmstate_scsw, SCSW),
119         VMSTATE_UINT64(mba, SCHIB),
120         VMSTATE_UINT8_ARRAY(mda, SCHIB, 4),
121         VMSTATE_END_OF_LIST()
122     }
123 };
124 
125 
126 static const VMStateDescription vmstate_ccw1 = {
127     .name = "s390_ccw1",
128     .version_id = 1,
129     .minimum_version_id = 1,
130     .fields = (VMStateField[]) {
131         VMSTATE_UINT8(cmd_code, CCW1),
132         VMSTATE_UINT8(flags, CCW1),
133         VMSTATE_UINT16(count, CCW1),
134         VMSTATE_UINT32(cda, CCW1),
135         VMSTATE_END_OF_LIST()
136     }
137 };
138 
139 static const VMStateDescription vmstate_ciw = {
140     .name = "s390_ciw",
141     .version_id = 1,
142     .minimum_version_id = 1,
143     .fields = (VMStateField[]) {
144         VMSTATE_UINT8(type, CIW),
145         VMSTATE_UINT8(command, CIW),
146         VMSTATE_UINT16(count, CIW),
147         VMSTATE_END_OF_LIST()
148     }
149 };
150 
151 static const VMStateDescription vmstate_sense_id = {
152     .name = "s390_sense_id",
153     .version_id = 1,
154     .minimum_version_id = 1,
155     .fields = (VMStateField[]) {
156         VMSTATE_UINT8(reserved, SenseId),
157         VMSTATE_UINT16(cu_type, SenseId),
158         VMSTATE_UINT8(cu_model, SenseId),
159         VMSTATE_UINT16(dev_type, SenseId),
160         VMSTATE_UINT8(dev_model, SenseId),
161         VMSTATE_UINT8(unused, SenseId),
162         VMSTATE_STRUCT_ARRAY(ciw, SenseId, MAX_CIWS, 0, vmstate_ciw, CIW),
163         VMSTATE_END_OF_LIST()
164     }
165 };
166 
167 static const VMStateDescription vmstate_orb = {
168     .name = "s390_orb",
169     .version_id = 1,
170     .minimum_version_id = 1,
171     .fields = (VMStateField[]) {
172         VMSTATE_UINT32(intparm, ORB),
173         VMSTATE_UINT16(ctrl0, ORB),
174         VMSTATE_UINT8(lpm, ORB),
175         VMSTATE_UINT8(ctrl1, ORB),
176         VMSTATE_UINT32(cpa, ORB),
177         VMSTATE_END_OF_LIST()
178     }
179 };
180 
181 static bool vmstate_schdev_orb_needed(void *opaque)
182 {
183     return css_migration_enabled();
184 }
185 
186 static const VMStateDescription vmstate_schdev_orb = {
187     .name = "s390_subch_dev/orb",
188     .version_id = 1,
189     .minimum_version_id = 1,
190     .needed = vmstate_schdev_orb_needed,
191     .fields = (VMStateField[]) {
192         VMSTATE_STRUCT(orb, SubchDev, 1, vmstate_orb, ORB),
193         VMSTATE_END_OF_LIST()
194     }
195 };
196 
197 static int subch_dev_post_load(void *opaque, int version_id);
198 static int subch_dev_pre_save(void *opaque);
199 
200 const char err_hint_devno[] = "Devno mismatch, tried to load wrong section!"
201     " Likely reason: some sequences of plug and unplug  can break"
202     " migration for machine versions prior to  2.7 (known design flaw).";
203 
204 const VMStateDescription vmstate_subch_dev = {
205     .name = "s390_subch_dev",
206     .version_id = 1,
207     .minimum_version_id = 1,
208     .post_load = subch_dev_post_load,
209     .pre_save = subch_dev_pre_save,
210     .fields = (VMStateField[]) {
211         VMSTATE_UINT8_EQUAL(cssid, SubchDev, "Bug!"),
212         VMSTATE_UINT8_EQUAL(ssid, SubchDev, "Bug!"),
213         VMSTATE_UINT16(migrated_schid, SubchDev),
214         VMSTATE_UINT16_EQUAL(devno, SubchDev, err_hint_devno),
215         VMSTATE_BOOL(thinint_active, SubchDev),
216         VMSTATE_STRUCT(curr_status, SubchDev, 0, vmstate_schib, SCHIB),
217         VMSTATE_UINT8_ARRAY(sense_data, SubchDev, 32),
218         VMSTATE_UINT64(channel_prog, SubchDev),
219         VMSTATE_STRUCT(last_cmd, SubchDev, 0, vmstate_ccw1, CCW1),
220         VMSTATE_BOOL(last_cmd_valid, SubchDev),
221         VMSTATE_STRUCT(id, SubchDev, 0, vmstate_sense_id, SenseId),
222         VMSTATE_BOOL(ccw_fmt_1, SubchDev),
223         VMSTATE_UINT8(ccw_no_data_cnt, SubchDev),
224         VMSTATE_END_OF_LIST()
225     },
226     .subsections = (const VMStateDescription * []) {
227         &vmstate_schdev_orb,
228         NULL
229     }
230 };
231 
232 typedef struct IndAddrPtrTmp {
233     IndAddr **parent;
234     uint64_t addr;
235     int32_t len;
236 } IndAddrPtrTmp;
237 
238 static int post_load_ind_addr(void *opaque, int version_id)
239 {
240     IndAddrPtrTmp *ptmp = opaque;
241     IndAddr **ind_addr = ptmp->parent;
242 
243     if (ptmp->len != 0) {
244         *ind_addr = get_indicator(ptmp->addr, ptmp->len);
245     } else {
246         *ind_addr = NULL;
247     }
248     return 0;
249 }
250 
251 static int pre_save_ind_addr(void *opaque)
252 {
253     IndAddrPtrTmp *ptmp = opaque;
254     IndAddr *ind_addr = *(ptmp->parent);
255 
256     if (ind_addr != NULL) {
257         ptmp->len = ind_addr->len;
258         ptmp->addr = ind_addr->addr;
259     } else {
260         ptmp->len = 0;
261         ptmp->addr = 0L;
262     }
263 
264     return 0;
265 }
266 
267 const VMStateDescription vmstate_ind_addr_tmp = {
268     .name = "s390_ind_addr_tmp",
269     .pre_save = pre_save_ind_addr,
270     .post_load = post_load_ind_addr,
271 
272     .fields = (VMStateField[]) {
273         VMSTATE_INT32(len, IndAddrPtrTmp),
274         VMSTATE_UINT64(addr, IndAddrPtrTmp),
275         VMSTATE_END_OF_LIST()
276     }
277 };
278 
279 const VMStateDescription vmstate_ind_addr = {
280     .name = "s390_ind_addr_tmp",
281     .fields = (VMStateField[]) {
282         VMSTATE_WITH_TMP(IndAddr*, IndAddrPtrTmp, vmstate_ind_addr_tmp),
283         VMSTATE_END_OF_LIST()
284     }
285 };
286 
287 typedef struct CssImage {
288     SubchSet *sch_set[MAX_SSID + 1];
289     ChpInfo chpids[MAX_CHPID + 1];
290 } CssImage;
291 
292 static const VMStateDescription vmstate_css_img = {
293     .name = "s390_css_img",
294     .version_id = 1,
295     .minimum_version_id = 1,
296     .fields = (VMStateField[]) {
297         /* Subchannel sets have no relevant state. */
298         VMSTATE_STRUCT_ARRAY(chpids, CssImage, MAX_CHPID + 1, 0,
299                              vmstate_chp_info, ChpInfo),
300         VMSTATE_END_OF_LIST()
301     }
302 
303 };
304 
305 typedef struct IoAdapter {
306     uint32_t id;
307     uint8_t type;
308     uint8_t isc;
309     uint8_t flags;
310 } IoAdapter;
311 
312 typedef struct ChannelSubSys {
313     QTAILQ_HEAD(, CrwContainer) pending_crws;
314     bool sei_pending;
315     bool do_crw_mchk;
316     bool crws_lost;
317     uint8_t max_cssid;
318     uint8_t max_ssid;
319     bool chnmon_active;
320     uint64_t chnmon_area;
321     CssImage *css[MAX_CSSID + 1];
322     uint8_t default_cssid;
323     /* don't migrate, see css_register_io_adapters */
324     IoAdapter *io_adapters[CSS_IO_ADAPTER_TYPE_NUMS][MAX_ISC + 1];
325     /* don't migrate, see get_indicator and IndAddrPtrTmp */
326     QTAILQ_HEAD(, IndAddr) indicator_addresses;
327 } ChannelSubSys;
328 
329 static const VMStateDescription vmstate_css = {
330     .name = "s390_css",
331     .version_id = 1,
332     .minimum_version_id = 1,
333     .fields = (VMStateField[]) {
334         VMSTATE_QTAILQ_V(pending_crws, ChannelSubSys, 1, vmstate_crw_container,
335                          CrwContainer, sibling),
336         VMSTATE_BOOL(sei_pending, ChannelSubSys),
337         VMSTATE_BOOL(do_crw_mchk, ChannelSubSys),
338         VMSTATE_BOOL(crws_lost, ChannelSubSys),
339         /* These were kind of migrated by virtio */
340         VMSTATE_UINT8(max_cssid, ChannelSubSys),
341         VMSTATE_UINT8(max_ssid, ChannelSubSys),
342         VMSTATE_BOOL(chnmon_active, ChannelSubSys),
343         VMSTATE_UINT64(chnmon_area, ChannelSubSys),
344         VMSTATE_ARRAY_OF_POINTER_TO_STRUCT(css, ChannelSubSys, MAX_CSSID + 1,
345                 0, vmstate_css_img, CssImage),
346         VMSTATE_UINT8(default_cssid, ChannelSubSys),
347         VMSTATE_END_OF_LIST()
348     }
349 };
350 
351 static ChannelSubSys channel_subsys = {
352     .pending_crws = QTAILQ_HEAD_INITIALIZER(channel_subsys.pending_crws),
353     .do_crw_mchk = true,
354     .sei_pending = false,
355     .do_crw_mchk = true,
356     .crws_lost = false,
357     .chnmon_active = false,
358     .indicator_addresses =
359         QTAILQ_HEAD_INITIALIZER(channel_subsys.indicator_addresses),
360 };
361 
362 static int subch_dev_pre_save(void *opaque)
363 {
364     SubchDev *s = opaque;
365 
366     /* Prepare remote_schid for save */
367     s->migrated_schid = s->schid;
368 
369     return 0;
370 }
371 
372 static int subch_dev_post_load(void *opaque, int version_id)
373 {
374 
375     SubchDev *s = opaque;
376 
377     /* Re-assign the subchannel to remote_schid if necessary */
378     if (s->migrated_schid != s->schid) {
379         if (css_find_subch(true, s->cssid, s->ssid, s->schid) == s) {
380             /*
381              * Cleanup the slot before moving to s->migrated_schid provided
382              * it still belongs to us, i.e. it was not changed by previous
383              * invocation of this function.
384              */
385             css_subch_assign(s->cssid, s->ssid, s->schid, s->devno, NULL);
386         }
387         /* It's OK to re-assign without a prior de-assign. */
388         s->schid = s->migrated_schid;
389         css_subch_assign(s->cssid, s->ssid, s->schid, s->devno, s);
390     }
391 
392     if (css_migration_enabled()) {
393         /* No compat voodoo to do ;) */
394         return 0;
395     }
396     /*
397      * Hack alert. If we don't migrate the channel subsystem status
398      * we still need to find out if the guest enabled mss/mcss-e.
399      * If the subchannel is enabled, it certainly was able to access it,
400      * so adjust the max_ssid/max_cssid values for relevant ssid/cssid
401      * values. This is not watertight, but better than nothing.
402      */
403     if (s->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ENA) {
404         if (s->ssid) {
405             channel_subsys.max_ssid = MAX_SSID;
406         }
407         if (s->cssid != channel_subsys.default_cssid) {
408             channel_subsys.max_cssid = MAX_CSSID;
409         }
410     }
411     return 0;
412 }
413 
414 void css_register_vmstate(void)
415 {
416     vmstate_register(NULL, 0, &vmstate_css, &channel_subsys);
417 }
418 
419 IndAddr *get_indicator(hwaddr ind_addr, int len)
420 {
421     IndAddr *indicator;
422 
423     QTAILQ_FOREACH(indicator, &channel_subsys.indicator_addresses, sibling) {
424         if (indicator->addr == ind_addr) {
425             indicator->refcnt++;
426             return indicator;
427         }
428     }
429     indicator = g_new0(IndAddr, 1);
430     indicator->addr = ind_addr;
431     indicator->len = len;
432     indicator->refcnt = 1;
433     QTAILQ_INSERT_TAIL(&channel_subsys.indicator_addresses,
434                        indicator, sibling);
435     return indicator;
436 }
437 
438 static int s390_io_adapter_map(AdapterInfo *adapter, uint64_t map_addr,
439                                bool do_map)
440 {
441     S390FLICState *fs = s390_get_flic();
442     S390FLICStateClass *fsc = s390_get_flic_class(fs);
443 
444     return fsc->io_adapter_map(fs, adapter->adapter_id, map_addr, do_map);
445 }
446 
447 void release_indicator(AdapterInfo *adapter, IndAddr *indicator)
448 {
449     assert(indicator->refcnt > 0);
450     indicator->refcnt--;
451     if (indicator->refcnt > 0) {
452         return;
453     }
454     QTAILQ_REMOVE(&channel_subsys.indicator_addresses, indicator, sibling);
455     if (indicator->map) {
456         s390_io_adapter_map(adapter, indicator->map, false);
457     }
458     g_free(indicator);
459 }
460 
461 int map_indicator(AdapterInfo *adapter, IndAddr *indicator)
462 {
463     int ret;
464 
465     if (indicator->map) {
466         return 0; /* already mapped is not an error */
467     }
468     indicator->map = indicator->addr;
469     ret = s390_io_adapter_map(adapter, indicator->map, true);
470     if ((ret != 0) && (ret != -ENOSYS)) {
471         goto out_err;
472     }
473     return 0;
474 
475 out_err:
476     indicator->map = 0;
477     return ret;
478 }
479 
480 int css_create_css_image(uint8_t cssid, bool default_image)
481 {
482     trace_css_new_image(cssid, default_image ? "(default)" : "");
483     /* 255 is reserved */
484     if (cssid == 255) {
485         return -EINVAL;
486     }
487     if (channel_subsys.css[cssid]) {
488         return -EBUSY;
489     }
490     channel_subsys.css[cssid] = g_new0(CssImage, 1);
491     if (default_image) {
492         channel_subsys.default_cssid = cssid;
493     }
494     return 0;
495 }
496 
497 uint32_t css_get_adapter_id(CssIoAdapterType type, uint8_t isc)
498 {
499     if (type >= CSS_IO_ADAPTER_TYPE_NUMS || isc > MAX_ISC ||
500         !channel_subsys.io_adapters[type][isc]) {
501         return -1;
502     }
503 
504     return channel_subsys.io_adapters[type][isc]->id;
505 }
506 
507 /**
508  * css_register_io_adapters: Register I/O adapters per ISC during init
509  *
510  * @swap: an indication if byte swap is needed.
511  * @maskable: an indication if the adapter is subject to the mask operation.
512  * @flags: further characteristics of the adapter.
513  *         e.g. suppressible, an indication if the adapter is subject to AIS.
514  * @errp: location to store error information.
515  */
516 void css_register_io_adapters(CssIoAdapterType type, bool swap, bool maskable,
517                               uint8_t flags, Error **errp)
518 {
519     uint32_t id;
520     int ret, isc;
521     IoAdapter *adapter;
522     S390FLICState *fs = s390_get_flic();
523     S390FLICStateClass *fsc = s390_get_flic_class(fs);
524 
525     /*
526      * Disallow multiple registrations for the same device type.
527      * Report an error if registering for an already registered type.
528      */
529     if (channel_subsys.io_adapters[type][0]) {
530         error_setg(errp, "Adapters for type %d already registered", type);
531     }
532 
533     for (isc = 0; isc <= MAX_ISC; isc++) {
534         id = (type << 3) | isc;
535         ret = fsc->register_io_adapter(fs, id, isc, swap, maskable, flags);
536         if (ret == 0) {
537             adapter = g_new0(IoAdapter, 1);
538             adapter->id = id;
539             adapter->isc = isc;
540             adapter->type = type;
541             adapter->flags = flags;
542             channel_subsys.io_adapters[type][isc] = adapter;
543         } else {
544             error_setg_errno(errp, -ret, "Unexpected error %d when "
545                              "registering adapter %d", ret, id);
546             break;
547         }
548     }
549 
550     /*
551      * No need to free registered adapters in kvm: kvm will clean up
552      * when the machine goes away.
553      */
554     if (ret) {
555         for (isc--; isc >= 0; isc--) {
556             g_free(channel_subsys.io_adapters[type][isc]);
557             channel_subsys.io_adapters[type][isc] = NULL;
558         }
559     }
560 
561 }
562 
563 static void css_clear_io_interrupt(uint16_t subchannel_id,
564                                    uint16_t subchannel_nr)
565 {
566     Error *err = NULL;
567     static bool no_clear_irq;
568     S390FLICState *fs = s390_get_flic();
569     S390FLICStateClass *fsc = s390_get_flic_class(fs);
570     int r;
571 
572     if (unlikely(no_clear_irq)) {
573         return;
574     }
575     r = fsc->clear_io_irq(fs, subchannel_id, subchannel_nr);
576     switch (r) {
577     case 0:
578         break;
579     case -ENOSYS:
580         no_clear_irq = true;
581         /*
582         * Ignore unavailability, as the user can't do anything
583         * about it anyway.
584         */
585         break;
586     default:
587         error_setg_errno(&err, -r, "unexpected error condition");
588         error_propagate(&error_abort, err);
589     }
590 }
591 
592 static inline uint16_t css_do_build_subchannel_id(uint8_t cssid, uint8_t ssid)
593 {
594     if (channel_subsys.max_cssid > 0) {
595         return (cssid << 8) | (1 << 3) | (ssid << 1) | 1;
596     }
597     return (ssid << 1) | 1;
598 }
599 
600 uint16_t css_build_subchannel_id(SubchDev *sch)
601 {
602     return css_do_build_subchannel_id(sch->cssid, sch->ssid);
603 }
604 
605 void css_inject_io_interrupt(SubchDev *sch)
606 {
607     uint8_t isc = (sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ISC) >> 11;
608 
609     trace_css_io_interrupt(sch->cssid, sch->ssid, sch->schid,
610                            sch->curr_status.pmcw.intparm, isc, "");
611     s390_io_interrupt(css_build_subchannel_id(sch),
612                       sch->schid,
613                       sch->curr_status.pmcw.intparm,
614                       isc << 27);
615 }
616 
617 void css_conditional_io_interrupt(SubchDev *sch)
618 {
619     /*
620      * If the subchannel is not enabled, it is not made status pending
621      * (see PoP p. 16-17, "Status Control").
622      */
623     if (!(sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ENA)) {
624         return;
625     }
626 
627     /*
628      * If the subchannel is not currently status pending, make it pending
629      * with alert status.
630      */
631     if (!(sch->curr_status.scsw.ctrl & SCSW_STCTL_STATUS_PEND)) {
632         uint8_t isc = (sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ISC) >> 11;
633 
634         trace_css_io_interrupt(sch->cssid, sch->ssid, sch->schid,
635                                sch->curr_status.pmcw.intparm, isc,
636                                "(unsolicited)");
637         sch->curr_status.scsw.ctrl &= ~SCSW_CTRL_MASK_STCTL;
638         sch->curr_status.scsw.ctrl |=
639             SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND;
640         /* Inject an I/O interrupt. */
641         s390_io_interrupt(css_build_subchannel_id(sch),
642                           sch->schid,
643                           sch->curr_status.pmcw.intparm,
644                           isc << 27);
645     }
646 }
647 
648 int css_do_sic(CPUS390XState *env, uint8_t isc, uint16_t mode)
649 {
650     S390FLICState *fs = s390_get_flic();
651     S390FLICStateClass *fsc = s390_get_flic_class(fs);
652     int r;
653 
654     if (env->psw.mask & PSW_MASK_PSTATE) {
655         r = -PGM_PRIVILEGED;
656         goto out;
657     }
658 
659     trace_css_do_sic(mode, isc);
660     switch (mode) {
661     case SIC_IRQ_MODE_ALL:
662     case SIC_IRQ_MODE_SINGLE:
663         break;
664     default:
665         r = -PGM_OPERAND;
666         goto out;
667     }
668 
669     r = fsc->modify_ais_mode(fs, isc, mode) ? -PGM_OPERATION : 0;
670 out:
671     return r;
672 }
673 
674 void css_adapter_interrupt(CssIoAdapterType type, uint8_t isc)
675 {
676     S390FLICState *fs = s390_get_flic();
677     S390FLICStateClass *fsc = s390_get_flic_class(fs);
678     uint32_t io_int_word = (isc << 27) | IO_INT_WORD_AI;
679     IoAdapter *adapter = channel_subsys.io_adapters[type][isc];
680 
681     if (!adapter) {
682         return;
683     }
684 
685     trace_css_adapter_interrupt(isc);
686     if (fs->ais_supported) {
687         if (fsc->inject_airq(fs, type, isc, adapter->flags)) {
688             error_report("Failed to inject airq with AIS supported");
689             exit(1);
690         }
691     } else {
692         s390_io_interrupt(0, 0, 0, io_int_word);
693     }
694 }
695 
696 static void sch_handle_clear_func(SubchDev *sch)
697 {
698     PMCW *p = &sch->curr_status.pmcw;
699     SCSW *s = &sch->curr_status.scsw;
700     int path;
701 
702     /* Path management: In our simple css, we always choose the only path. */
703     path = 0x80;
704 
705     /* Reset values prior to 'issuing the clear signal'. */
706     p->lpum = 0;
707     p->pom = 0xff;
708     s->flags &= ~SCSW_FLAGS_MASK_PNO;
709 
710     /* We always 'attempt to issue the clear signal', and we always succeed. */
711     sch->channel_prog = 0x0;
712     sch->last_cmd_valid = false;
713     s->ctrl &= ~SCSW_ACTL_CLEAR_PEND;
714     s->ctrl |= SCSW_STCTL_STATUS_PEND;
715 
716     s->dstat = 0;
717     s->cstat = 0;
718     p->lpum = path;
719 
720 }
721 
722 static void sch_handle_halt_func(SubchDev *sch)
723 {
724 
725     PMCW *p = &sch->curr_status.pmcw;
726     SCSW *s = &sch->curr_status.scsw;
727     hwaddr curr_ccw = sch->channel_prog;
728     int path;
729 
730     /* Path management: In our simple css, we always choose the only path. */
731     path = 0x80;
732 
733     /* We always 'attempt to issue the halt signal', and we always succeed. */
734     sch->channel_prog = 0x0;
735     sch->last_cmd_valid = false;
736     s->ctrl &= ~SCSW_ACTL_HALT_PEND;
737     s->ctrl |= SCSW_STCTL_STATUS_PEND;
738 
739     if ((s->ctrl & (SCSW_ACTL_SUBCH_ACTIVE | SCSW_ACTL_DEVICE_ACTIVE)) ||
740         !((s->ctrl & SCSW_ACTL_START_PEND) ||
741           (s->ctrl & SCSW_ACTL_SUSP))) {
742         s->dstat = SCSW_DSTAT_DEVICE_END;
743     }
744     if ((s->ctrl & (SCSW_ACTL_SUBCH_ACTIVE | SCSW_ACTL_DEVICE_ACTIVE)) ||
745         (s->ctrl & SCSW_ACTL_SUSP)) {
746         s->cpa = curr_ccw + 8;
747     }
748     s->cstat = 0;
749     p->lpum = path;
750 
751 }
752 
753 /*
754  * As the SenseId struct cannot be packed (would cause unaligned accesses), we
755  * have to copy the individual fields to an unstructured area using the correct
756  * layout (see SA22-7204-01 "Common I/O-Device Commands").
757  */
758 static void copy_sense_id_to_guest(uint8_t *dest, SenseId *src)
759 {
760     int i;
761 
762     dest[0] = src->reserved;
763     stw_be_p(dest + 1, src->cu_type);
764     dest[3] = src->cu_model;
765     stw_be_p(dest + 4, src->dev_type);
766     dest[6] = src->dev_model;
767     dest[7] = src->unused;
768     for (i = 0; i < ARRAY_SIZE(src->ciw); i++) {
769         dest[8 + i * 4] = src->ciw[i].type;
770         dest[9 + i * 4] = src->ciw[i].command;
771         stw_be_p(dest + 10 + i * 4, src->ciw[i].count);
772     }
773 }
774 
775 static CCW1 copy_ccw_from_guest(hwaddr addr, bool fmt1)
776 {
777     CCW0 tmp0;
778     CCW1 tmp1;
779     CCW1 ret;
780 
781     if (fmt1) {
782         cpu_physical_memory_read(addr, &tmp1, sizeof(tmp1));
783         ret.cmd_code = tmp1.cmd_code;
784         ret.flags = tmp1.flags;
785         ret.count = be16_to_cpu(tmp1.count);
786         ret.cda = be32_to_cpu(tmp1.cda);
787     } else {
788         cpu_physical_memory_read(addr, &tmp0, sizeof(tmp0));
789         if ((tmp0.cmd_code & 0x0f) == CCW_CMD_TIC) {
790             ret.cmd_code = CCW_CMD_TIC;
791             ret.flags = 0;
792             ret.count = 0;
793         } else {
794             ret.cmd_code = tmp0.cmd_code;
795             ret.flags = tmp0.flags;
796             ret.count = be16_to_cpu(tmp0.count);
797         }
798         ret.cda = be16_to_cpu(tmp0.cda1) | (tmp0.cda0 << 16);
799     }
800     return ret;
801 }
802 /**
803  * If out of bounds marks the stream broken. If broken returns -EINVAL,
804  * otherwise the requested length (may be zero)
805  */
806 static inline int cds_check_len(CcwDataStream *cds, int len)
807 {
808     if (cds->at_byte + len > cds->count) {
809         cds->flags |= CDS_F_STREAM_BROKEN;
810     }
811     return cds->flags & CDS_F_STREAM_BROKEN ? -EINVAL : len;
812 }
813 
814 static inline bool cds_ccw_addrs_ok(hwaddr addr, int len, bool ccw_fmt1)
815 {
816     return (addr + len) < (ccw_fmt1 ? (1UL << 31) : (1UL << 24));
817 }
818 
819 static int ccw_dstream_rw_noflags(CcwDataStream *cds, void *buff, int len,
820                                   CcwDataStreamOp op)
821 {
822     int ret;
823 
824     ret = cds_check_len(cds, len);
825     if (ret <= 0) {
826         return ret;
827     }
828     if (!cds_ccw_addrs_ok(cds->cda, len, cds->flags & CDS_F_FMT)) {
829         return -EINVAL; /* channel program check */
830     }
831     if (op == CDS_OP_A) {
832         goto incr;
833     }
834     ret = address_space_rw(&address_space_memory, cds->cda,
835                            MEMTXATTRS_UNSPECIFIED, buff, len, op);
836     if (ret != MEMTX_OK) {
837         cds->flags |= CDS_F_STREAM_BROKEN;
838         return -EINVAL;
839     }
840 incr:
841     cds->at_byte += len;
842     cds->cda += len;
843     return 0;
844 }
845 
846 /* returns values between 1 and bsz, where bsz is a power of 2 */
847 static inline uint16_t ida_continuous_left(hwaddr cda, uint64_t bsz)
848 {
849     return bsz - (cda & (bsz - 1));
850 }
851 
852 static inline uint64_t ccw_ida_block_size(uint8_t flags)
853 {
854     if ((flags & CDS_F_C64) && !(flags & CDS_F_I2K)) {
855         return 1ULL << 12;
856     }
857     return 1ULL << 11;
858 }
859 
860 static inline int ida_read_next_idaw(CcwDataStream *cds)
861 {
862     union {uint64_t fmt2; uint32_t fmt1; } idaw;
863     int ret;
864     hwaddr idaw_addr;
865     bool idaw_fmt2 = cds->flags & CDS_F_C64;
866     bool ccw_fmt1 = cds->flags & CDS_F_FMT;
867 
868     if (idaw_fmt2) {
869         idaw_addr = cds->cda_orig + sizeof(idaw.fmt2) * cds->at_idaw;
870         if (idaw_addr & 0x07 || !cds_ccw_addrs_ok(idaw_addr, 0, ccw_fmt1)) {
871             return -EINVAL; /* channel program check */
872         }
873         ret = address_space_rw(&address_space_memory, idaw_addr,
874                                MEMTXATTRS_UNSPECIFIED, (void *) &idaw.fmt2,
875                                sizeof(idaw.fmt2), false);
876         cds->cda = be64_to_cpu(idaw.fmt2);
877     } else {
878         idaw_addr = cds->cda_orig + sizeof(idaw.fmt1) * cds->at_idaw;
879         if (idaw_addr & 0x03 || !cds_ccw_addrs_ok(idaw_addr, 0, ccw_fmt1)) {
880             return -EINVAL; /* channel program check */
881         }
882         ret = address_space_rw(&address_space_memory, idaw_addr,
883                                MEMTXATTRS_UNSPECIFIED, (void *) &idaw.fmt1,
884                                sizeof(idaw.fmt1), false);
885         cds->cda = be64_to_cpu(idaw.fmt1);
886         if (cds->cda & 0x80000000) {
887             return -EINVAL; /* channel program check */
888         }
889     }
890     ++(cds->at_idaw);
891     if (ret != MEMTX_OK) {
892         /* assume inaccessible address */
893         return -EINVAL; /* channel program check */
894     }
895     return 0;
896 }
897 
898 static int ccw_dstream_rw_ida(CcwDataStream *cds, void *buff, int len,
899                               CcwDataStreamOp op)
900 {
901     uint64_t bsz = ccw_ida_block_size(cds->flags);
902     int ret = 0;
903     uint16_t cont_left, iter_len;
904 
905     ret = cds_check_len(cds, len);
906     if (ret <= 0) {
907         return ret;
908     }
909     if (!cds->at_idaw) {
910         /* read first idaw */
911         ret = ida_read_next_idaw(cds);
912         if (ret) {
913             goto err;
914         }
915         cont_left = ida_continuous_left(cds->cda, bsz);
916     } else {
917         cont_left = ida_continuous_left(cds->cda, bsz);
918         if (cont_left == bsz) {
919             ret = ida_read_next_idaw(cds);
920             if (ret) {
921                 goto err;
922             }
923             if (cds->cda & (bsz - 1)) {
924                 ret = -EINVAL; /* channel program check */
925                 goto err;
926             }
927         }
928     }
929     do {
930         iter_len = MIN(len, cont_left);
931         if (op != CDS_OP_A) {
932             ret = address_space_rw(&address_space_memory, cds->cda,
933                                    MEMTXATTRS_UNSPECIFIED, buff, iter_len, op);
934             if (ret != MEMTX_OK) {
935                 /* assume inaccessible address */
936                 ret = -EINVAL; /* channel program check */
937                 goto err;
938             }
939         }
940         cds->at_byte += iter_len;
941         cds->cda += iter_len;
942         len -= iter_len;
943         if (!len) {
944             break;
945         }
946         ret = ida_read_next_idaw(cds);
947         if (ret) {
948             goto err;
949         }
950         cont_left = bsz;
951     } while (true);
952     return ret;
953 err:
954     cds->flags |= CDS_F_STREAM_BROKEN;
955     return ret;
956 }
957 
958 void ccw_dstream_init(CcwDataStream *cds, CCW1 const *ccw, ORB const *orb)
959 {
960     /*
961      * We don't support MIDA (an optional facility) yet and we
962      * catch this earlier. Just for expressing the precondition.
963      */
964     g_assert(!(orb->ctrl1 & ORB_CTRL1_MASK_MIDAW));
965     cds->flags = (orb->ctrl0 & ORB_CTRL0_MASK_I2K ? CDS_F_I2K : 0) |
966                  (orb->ctrl0 & ORB_CTRL0_MASK_C64 ? CDS_F_C64 : 0) |
967                  (orb->ctrl0 & ORB_CTRL0_MASK_FMT ? CDS_F_FMT : 0) |
968                  (ccw->flags & CCW_FLAG_IDA ? CDS_F_IDA : 0);
969 
970     cds->count = ccw->count;
971     cds->cda_orig = ccw->cda;
972     ccw_dstream_rewind(cds);
973     if (!(cds->flags & CDS_F_IDA)) {
974         cds->op_handler = ccw_dstream_rw_noflags;
975     } else {
976         cds->op_handler = ccw_dstream_rw_ida;
977     }
978 }
979 
980 static int css_interpret_ccw(SubchDev *sch, hwaddr ccw_addr,
981                              bool suspend_allowed)
982 {
983     int ret;
984     bool check_len;
985     int len;
986     CCW1 ccw;
987 
988     if (!ccw_addr) {
989         return -EINVAL; /* channel-program check */
990     }
991     /* Check doubleword aligned and 31 or 24 (fmt 0) bit addressable. */
992     if (ccw_addr & (sch->ccw_fmt_1 ? 0x80000007 : 0xff000007)) {
993         return -EINVAL;
994     }
995 
996     /* Translate everything to format-1 ccws - the information is the same. */
997     ccw = copy_ccw_from_guest(ccw_addr, sch->ccw_fmt_1);
998 
999     /* Check for invalid command codes. */
1000     if ((ccw.cmd_code & 0x0f) == 0) {
1001         return -EINVAL;
1002     }
1003     if (((ccw.cmd_code & 0x0f) == CCW_CMD_TIC) &&
1004         ((ccw.cmd_code & 0xf0) != 0)) {
1005         return -EINVAL;
1006     }
1007     if (!sch->ccw_fmt_1 && (ccw.count == 0) &&
1008         (ccw.cmd_code != CCW_CMD_TIC)) {
1009         return -EINVAL;
1010     }
1011 
1012     /* We don't support MIDA. */
1013     if (ccw.flags & CCW_FLAG_MIDA) {
1014         return -EINVAL;
1015     }
1016 
1017     if (ccw.flags & CCW_FLAG_SUSPEND) {
1018         return suspend_allowed ? -EINPROGRESS : -EINVAL;
1019     }
1020 
1021     check_len = !((ccw.flags & CCW_FLAG_SLI) && !(ccw.flags & CCW_FLAG_DC));
1022 
1023     if (!ccw.cda) {
1024         if (sch->ccw_no_data_cnt == 255) {
1025             return -EINVAL;
1026         }
1027         sch->ccw_no_data_cnt++;
1028     }
1029 
1030     /* Look at the command. */
1031     ccw_dstream_init(&sch->cds, &ccw, &(sch->orb));
1032     switch (ccw.cmd_code) {
1033     case CCW_CMD_NOOP:
1034         /* Nothing to do. */
1035         ret = 0;
1036         break;
1037     case CCW_CMD_BASIC_SENSE:
1038         if (check_len) {
1039             if (ccw.count != sizeof(sch->sense_data)) {
1040                 ret = -EINVAL;
1041                 break;
1042             }
1043         }
1044         len = MIN(ccw.count, sizeof(sch->sense_data));
1045         ccw_dstream_write_buf(&sch->cds, sch->sense_data, len);
1046         sch->curr_status.scsw.count = ccw_dstream_residual_count(&sch->cds);
1047         memset(sch->sense_data, 0, sizeof(sch->sense_data));
1048         ret = 0;
1049         break;
1050     case CCW_CMD_SENSE_ID:
1051     {
1052         /* According to SA22-7204-01, Sense-ID can store up to 256 bytes */
1053         uint8_t sense_id[256];
1054 
1055         copy_sense_id_to_guest(sense_id, &sch->id);
1056         /* Sense ID information is device specific. */
1057         if (check_len) {
1058             if (ccw.count != sizeof(sense_id)) {
1059                 ret = -EINVAL;
1060                 break;
1061             }
1062         }
1063         len = MIN(ccw.count, sizeof(sense_id));
1064         /*
1065          * Only indicate 0xff in the first sense byte if we actually
1066          * have enough place to store at least bytes 0-3.
1067          */
1068         if (len >= 4) {
1069             sense_id[0] = 0xff;
1070         } else {
1071             sense_id[0] = 0;
1072         }
1073         ccw_dstream_write_buf(&sch->cds, sense_id, len);
1074         sch->curr_status.scsw.count = ccw_dstream_residual_count(&sch->cds);
1075         ret = 0;
1076         break;
1077     }
1078     case CCW_CMD_TIC:
1079         if (sch->last_cmd_valid && (sch->last_cmd.cmd_code == CCW_CMD_TIC)) {
1080             ret = -EINVAL;
1081             break;
1082         }
1083         if (ccw.flags || ccw.count) {
1084             /* We have already sanitized these if converted from fmt 0. */
1085             ret = -EINVAL;
1086             break;
1087         }
1088         sch->channel_prog = ccw.cda;
1089         ret = -EAGAIN;
1090         break;
1091     default:
1092         if (sch->ccw_cb) {
1093             /* Handle device specific commands. */
1094             ret = sch->ccw_cb(sch, ccw);
1095         } else {
1096             ret = -ENOSYS;
1097         }
1098         break;
1099     }
1100     sch->last_cmd = ccw;
1101     sch->last_cmd_valid = true;
1102     if (ret == 0) {
1103         if (ccw.flags & CCW_FLAG_CC) {
1104             sch->channel_prog += 8;
1105             ret = -EAGAIN;
1106         }
1107     }
1108 
1109     return ret;
1110 }
1111 
1112 static void sch_handle_start_func_virtual(SubchDev *sch)
1113 {
1114 
1115     PMCW *p = &sch->curr_status.pmcw;
1116     SCSW *s = &sch->curr_status.scsw;
1117     int path;
1118     int ret;
1119     bool suspend_allowed;
1120 
1121     /* Path management: In our simple css, we always choose the only path. */
1122     path = 0x80;
1123 
1124     if (!(s->ctrl & SCSW_ACTL_SUSP)) {
1125         /* Start Function triggered via ssch, i.e. we have an ORB */
1126         ORB *orb = &sch->orb;
1127         s->cstat = 0;
1128         s->dstat = 0;
1129         /* Look at the orb and try to execute the channel program. */
1130         p->intparm = orb->intparm;
1131         if (!(orb->lpm & path)) {
1132             /* Generate a deferred cc 3 condition. */
1133             s->flags |= SCSW_FLAGS_MASK_CC;
1134             s->ctrl &= ~SCSW_CTRL_MASK_STCTL;
1135             s->ctrl |= (SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND);
1136             return;
1137         }
1138         sch->ccw_fmt_1 = !!(orb->ctrl0 & ORB_CTRL0_MASK_FMT);
1139         s->flags |= (sch->ccw_fmt_1) ? SCSW_FLAGS_MASK_FMT : 0;
1140         sch->ccw_no_data_cnt = 0;
1141         suspend_allowed = !!(orb->ctrl0 & ORB_CTRL0_MASK_SPND);
1142     } else {
1143         /* Start Function resumed via rsch */
1144         s->ctrl &= ~(SCSW_ACTL_SUSP | SCSW_ACTL_RESUME_PEND);
1145         /* The channel program had been suspended before. */
1146         suspend_allowed = true;
1147     }
1148     sch->last_cmd_valid = false;
1149     do {
1150         ret = css_interpret_ccw(sch, sch->channel_prog, suspend_allowed);
1151         switch (ret) {
1152         case -EAGAIN:
1153             /* ccw chain, continue processing */
1154             break;
1155         case 0:
1156             /* success */
1157             s->ctrl &= ~SCSW_ACTL_START_PEND;
1158             s->ctrl &= ~SCSW_CTRL_MASK_STCTL;
1159             s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY |
1160                     SCSW_STCTL_STATUS_PEND;
1161             s->dstat = SCSW_DSTAT_CHANNEL_END | SCSW_DSTAT_DEVICE_END;
1162             s->cpa = sch->channel_prog + 8;
1163             break;
1164         case -EIO:
1165             /* I/O errors, status depends on specific devices */
1166             break;
1167         case -ENOSYS:
1168             /* unsupported command, generate unit check (command reject) */
1169             s->ctrl &= ~SCSW_ACTL_START_PEND;
1170             s->dstat = SCSW_DSTAT_UNIT_CHECK;
1171             /* Set sense bit 0 in ecw0. */
1172             sch->sense_data[0] = 0x80;
1173             s->ctrl &= ~SCSW_CTRL_MASK_STCTL;
1174             s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY |
1175                     SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND;
1176             s->cpa = sch->channel_prog + 8;
1177             break;
1178         case -EINPROGRESS:
1179             /* channel program has been suspended */
1180             s->ctrl &= ~SCSW_ACTL_START_PEND;
1181             s->ctrl |= SCSW_ACTL_SUSP;
1182             break;
1183         default:
1184             /* error, generate channel program check */
1185             s->ctrl &= ~SCSW_ACTL_START_PEND;
1186             s->cstat = SCSW_CSTAT_PROG_CHECK;
1187             s->ctrl &= ~SCSW_CTRL_MASK_STCTL;
1188             s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY |
1189                     SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND;
1190             s->cpa = sch->channel_prog + 8;
1191             break;
1192         }
1193     } while (ret == -EAGAIN);
1194 
1195 }
1196 
1197 static IOInstEnding sch_handle_start_func_passthrough(SubchDev *sch)
1198 {
1199 
1200     PMCW *p = &sch->curr_status.pmcw;
1201     SCSW *s = &sch->curr_status.scsw;
1202 
1203     ORB *orb = &sch->orb;
1204     if (!(s->ctrl & SCSW_ACTL_SUSP)) {
1205         assert(orb != NULL);
1206         p->intparm = orb->intparm;
1207     }
1208     return s390_ccw_cmd_request(sch);
1209 }
1210 
1211 /*
1212  * On real machines, this would run asynchronously to the main vcpus.
1213  * We might want to make some parts of the ssch handling (interpreting
1214  * read/writes) asynchronous later on if we start supporting more than
1215  * our current very simple devices.
1216  */
1217 IOInstEnding do_subchannel_work_virtual(SubchDev *sch)
1218 {
1219 
1220     SCSW *s = &sch->curr_status.scsw;
1221 
1222     if (s->ctrl & SCSW_FCTL_CLEAR_FUNC) {
1223         sch_handle_clear_func(sch);
1224     } else if (s->ctrl & SCSW_FCTL_HALT_FUNC) {
1225         sch_handle_halt_func(sch);
1226     } else if (s->ctrl & SCSW_FCTL_START_FUNC) {
1227         /* Triggered by both ssch and rsch. */
1228         sch_handle_start_func_virtual(sch);
1229     }
1230     css_inject_io_interrupt(sch);
1231     /* inst must succeed if this func is called */
1232     return IOINST_CC_EXPECTED;
1233 }
1234 
1235 IOInstEnding do_subchannel_work_passthrough(SubchDev *sch)
1236 {
1237     SCSW *s = &sch->curr_status.scsw;
1238 
1239     if (s->ctrl & SCSW_FCTL_CLEAR_FUNC) {
1240         /* TODO: Clear handling */
1241         sch_handle_clear_func(sch);
1242     } else if (s->ctrl & SCSW_FCTL_HALT_FUNC) {
1243         /* TODO: Halt handling */
1244         sch_handle_halt_func(sch);
1245     } else if (s->ctrl & SCSW_FCTL_START_FUNC) {
1246         return sch_handle_start_func_passthrough(sch);
1247     }
1248     return IOINST_CC_EXPECTED;
1249 }
1250 
1251 static IOInstEnding do_subchannel_work(SubchDev *sch)
1252 {
1253     if (!sch->do_subchannel_work) {
1254         return IOINST_CC_STATUS_PRESENT;
1255     }
1256     g_assert(sch->curr_status.scsw.ctrl & SCSW_CTRL_MASK_FCTL);
1257     return sch->do_subchannel_work(sch);
1258 }
1259 
1260 static void copy_pmcw_to_guest(PMCW *dest, const PMCW *src)
1261 {
1262     int i;
1263 
1264     dest->intparm = cpu_to_be32(src->intparm);
1265     dest->flags = cpu_to_be16(src->flags);
1266     dest->devno = cpu_to_be16(src->devno);
1267     dest->lpm = src->lpm;
1268     dest->pnom = src->pnom;
1269     dest->lpum = src->lpum;
1270     dest->pim = src->pim;
1271     dest->mbi = cpu_to_be16(src->mbi);
1272     dest->pom = src->pom;
1273     dest->pam = src->pam;
1274     for (i = 0; i < ARRAY_SIZE(dest->chpid); i++) {
1275         dest->chpid[i] = src->chpid[i];
1276     }
1277     dest->chars = cpu_to_be32(src->chars);
1278 }
1279 
1280 void copy_scsw_to_guest(SCSW *dest, const SCSW *src)
1281 {
1282     dest->flags = cpu_to_be16(src->flags);
1283     dest->ctrl = cpu_to_be16(src->ctrl);
1284     dest->cpa = cpu_to_be32(src->cpa);
1285     dest->dstat = src->dstat;
1286     dest->cstat = src->cstat;
1287     dest->count = cpu_to_be16(src->count);
1288 }
1289 
1290 static void copy_schib_to_guest(SCHIB *dest, const SCHIB *src)
1291 {
1292     int i;
1293     /*
1294      * We copy the PMCW and SCSW in and out of local variables to
1295      * avoid taking the address of members of a packed struct.
1296      */
1297     PMCW src_pmcw, dest_pmcw;
1298     SCSW src_scsw, dest_scsw;
1299 
1300     src_pmcw = src->pmcw;
1301     copy_pmcw_to_guest(&dest_pmcw, &src_pmcw);
1302     dest->pmcw = dest_pmcw;
1303     src_scsw = src->scsw;
1304     copy_scsw_to_guest(&dest_scsw, &src_scsw);
1305     dest->scsw = dest_scsw;
1306     dest->mba = cpu_to_be64(src->mba);
1307     for (i = 0; i < ARRAY_SIZE(dest->mda); i++) {
1308         dest->mda[i] = src->mda[i];
1309     }
1310 }
1311 
1312 int css_do_stsch(SubchDev *sch, SCHIB *schib)
1313 {
1314     /* Use current status. */
1315     copy_schib_to_guest(schib, &sch->curr_status);
1316     return 0;
1317 }
1318 
1319 static void copy_pmcw_from_guest(PMCW *dest, const PMCW *src)
1320 {
1321     int i;
1322 
1323     dest->intparm = be32_to_cpu(src->intparm);
1324     dest->flags = be16_to_cpu(src->flags);
1325     dest->devno = be16_to_cpu(src->devno);
1326     dest->lpm = src->lpm;
1327     dest->pnom = src->pnom;
1328     dest->lpum = src->lpum;
1329     dest->pim = src->pim;
1330     dest->mbi = be16_to_cpu(src->mbi);
1331     dest->pom = src->pom;
1332     dest->pam = src->pam;
1333     for (i = 0; i < ARRAY_SIZE(dest->chpid); i++) {
1334         dest->chpid[i] = src->chpid[i];
1335     }
1336     dest->chars = be32_to_cpu(src->chars);
1337 }
1338 
1339 static void copy_scsw_from_guest(SCSW *dest, const SCSW *src)
1340 {
1341     dest->flags = be16_to_cpu(src->flags);
1342     dest->ctrl = be16_to_cpu(src->ctrl);
1343     dest->cpa = be32_to_cpu(src->cpa);
1344     dest->dstat = src->dstat;
1345     dest->cstat = src->cstat;
1346     dest->count = be16_to_cpu(src->count);
1347 }
1348 
1349 static void copy_schib_from_guest(SCHIB *dest, const SCHIB *src)
1350 {
1351     int i;
1352     /*
1353      * We copy the PMCW and SCSW in and out of local variables to
1354      * avoid taking the address of members of a packed struct.
1355      */
1356     PMCW src_pmcw, dest_pmcw;
1357     SCSW src_scsw, dest_scsw;
1358 
1359     src_pmcw = src->pmcw;
1360     copy_pmcw_from_guest(&dest_pmcw, &src_pmcw);
1361     dest->pmcw = dest_pmcw;
1362     src_scsw = src->scsw;
1363     copy_scsw_from_guest(&dest_scsw, &src_scsw);
1364     dest->scsw = dest_scsw;
1365     dest->mba = be64_to_cpu(src->mba);
1366     for (i = 0; i < ARRAY_SIZE(dest->mda); i++) {
1367         dest->mda[i] = src->mda[i];
1368     }
1369 }
1370 
1371 IOInstEnding css_do_msch(SubchDev *sch, const SCHIB *orig_schib)
1372 {
1373     SCSW *s = &sch->curr_status.scsw;
1374     PMCW *p = &sch->curr_status.pmcw;
1375     uint16_t oldflags;
1376     SCHIB schib;
1377 
1378     if (!(sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_DNV)) {
1379         return IOINST_CC_EXPECTED;
1380     }
1381 
1382     if (s->ctrl & SCSW_STCTL_STATUS_PEND) {
1383         return IOINST_CC_STATUS_PRESENT;
1384     }
1385 
1386     if (s->ctrl &
1387         (SCSW_FCTL_START_FUNC|SCSW_FCTL_HALT_FUNC|SCSW_FCTL_CLEAR_FUNC)) {
1388         return IOINST_CC_BUSY;
1389     }
1390 
1391     copy_schib_from_guest(&schib, orig_schib);
1392     /* Only update the program-modifiable fields. */
1393     p->intparm = schib.pmcw.intparm;
1394     oldflags = p->flags;
1395     p->flags &= ~(PMCW_FLAGS_MASK_ISC | PMCW_FLAGS_MASK_ENA |
1396                   PMCW_FLAGS_MASK_LM | PMCW_FLAGS_MASK_MME |
1397                   PMCW_FLAGS_MASK_MP);
1398     p->flags |= schib.pmcw.flags &
1399             (PMCW_FLAGS_MASK_ISC | PMCW_FLAGS_MASK_ENA |
1400              PMCW_FLAGS_MASK_LM | PMCW_FLAGS_MASK_MME |
1401              PMCW_FLAGS_MASK_MP);
1402     p->lpm = schib.pmcw.lpm;
1403     p->mbi = schib.pmcw.mbi;
1404     p->pom = schib.pmcw.pom;
1405     p->chars &= ~(PMCW_CHARS_MASK_MBFC | PMCW_CHARS_MASK_CSENSE);
1406     p->chars |= schib.pmcw.chars &
1407             (PMCW_CHARS_MASK_MBFC | PMCW_CHARS_MASK_CSENSE);
1408     sch->curr_status.mba = schib.mba;
1409 
1410     /* Has the channel been disabled? */
1411     if (sch->disable_cb && (oldflags & PMCW_FLAGS_MASK_ENA) != 0
1412         && (p->flags & PMCW_FLAGS_MASK_ENA) == 0) {
1413         sch->disable_cb(sch);
1414     }
1415     return IOINST_CC_EXPECTED;
1416 }
1417 
1418 IOInstEnding css_do_xsch(SubchDev *sch)
1419 {
1420     SCSW *s = &sch->curr_status.scsw;
1421     PMCW *p = &sch->curr_status.pmcw;
1422 
1423     if (~(p->flags) & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA)) {
1424         return IOINST_CC_NOT_OPERATIONAL;
1425     }
1426 
1427     if (s->ctrl & SCSW_CTRL_MASK_STCTL) {
1428         return IOINST_CC_STATUS_PRESENT;
1429     }
1430 
1431     if (!(s->ctrl & SCSW_CTRL_MASK_FCTL) ||
1432         ((s->ctrl & SCSW_CTRL_MASK_FCTL) != SCSW_FCTL_START_FUNC) ||
1433         (!(s->ctrl &
1434            (SCSW_ACTL_RESUME_PEND | SCSW_ACTL_START_PEND | SCSW_ACTL_SUSP))) ||
1435         (s->ctrl & SCSW_ACTL_SUBCH_ACTIVE)) {
1436         return IOINST_CC_BUSY;
1437     }
1438 
1439     /* Cancel the current operation. */
1440     s->ctrl &= ~(SCSW_FCTL_START_FUNC |
1441                  SCSW_ACTL_RESUME_PEND |
1442                  SCSW_ACTL_START_PEND |
1443                  SCSW_ACTL_SUSP);
1444     sch->channel_prog = 0x0;
1445     sch->last_cmd_valid = false;
1446     s->dstat = 0;
1447     s->cstat = 0;
1448     return IOINST_CC_EXPECTED;
1449 }
1450 
1451 IOInstEnding css_do_csch(SubchDev *sch)
1452 {
1453     SCSW *s = &sch->curr_status.scsw;
1454     PMCW *p = &sch->curr_status.pmcw;
1455 
1456     if (~(p->flags) & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA)) {
1457         return IOINST_CC_NOT_OPERATIONAL;
1458     }
1459 
1460     /* Trigger the clear function. */
1461     s->ctrl &= ~(SCSW_CTRL_MASK_FCTL | SCSW_CTRL_MASK_ACTL);
1462     s->ctrl |= SCSW_FCTL_CLEAR_FUNC | SCSW_ACTL_CLEAR_PEND;
1463 
1464     return do_subchannel_work(sch);
1465 }
1466 
1467 IOInstEnding css_do_hsch(SubchDev *sch)
1468 {
1469     SCSW *s = &sch->curr_status.scsw;
1470     PMCW *p = &sch->curr_status.pmcw;
1471 
1472     if (~(p->flags) & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA)) {
1473         return IOINST_CC_NOT_OPERATIONAL;
1474     }
1475 
1476     if (((s->ctrl & SCSW_CTRL_MASK_STCTL) == SCSW_STCTL_STATUS_PEND) ||
1477         (s->ctrl & (SCSW_STCTL_PRIMARY |
1478                     SCSW_STCTL_SECONDARY |
1479                     SCSW_STCTL_ALERT))) {
1480         return IOINST_CC_STATUS_PRESENT;
1481     }
1482 
1483     if (s->ctrl & (SCSW_FCTL_HALT_FUNC | SCSW_FCTL_CLEAR_FUNC)) {
1484         return IOINST_CC_BUSY;
1485     }
1486 
1487     /* Trigger the halt function. */
1488     s->ctrl |= SCSW_FCTL_HALT_FUNC;
1489     s->ctrl &= ~SCSW_FCTL_START_FUNC;
1490     if (((s->ctrl & SCSW_CTRL_MASK_ACTL) ==
1491          (SCSW_ACTL_SUBCH_ACTIVE | SCSW_ACTL_DEVICE_ACTIVE)) &&
1492         ((s->ctrl & SCSW_CTRL_MASK_STCTL) == SCSW_STCTL_INTERMEDIATE)) {
1493         s->ctrl &= ~SCSW_STCTL_STATUS_PEND;
1494     }
1495     s->ctrl |= SCSW_ACTL_HALT_PEND;
1496 
1497     return do_subchannel_work(sch);
1498 }
1499 
1500 static void css_update_chnmon(SubchDev *sch)
1501 {
1502     if (!(sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_MME)) {
1503         /* Not active. */
1504         return;
1505     }
1506     /* The counter is conveniently located at the beginning of the struct. */
1507     if (sch->curr_status.pmcw.chars & PMCW_CHARS_MASK_MBFC) {
1508         /* Format 1, per-subchannel area. */
1509         uint32_t count;
1510 
1511         count = address_space_ldl(&address_space_memory,
1512                                   sch->curr_status.mba,
1513                                   MEMTXATTRS_UNSPECIFIED,
1514                                   NULL);
1515         count++;
1516         address_space_stl(&address_space_memory, sch->curr_status.mba, count,
1517                           MEMTXATTRS_UNSPECIFIED, NULL);
1518     } else {
1519         /* Format 0, global area. */
1520         uint32_t offset;
1521         uint16_t count;
1522 
1523         offset = sch->curr_status.pmcw.mbi << 5;
1524         count = address_space_lduw(&address_space_memory,
1525                                    channel_subsys.chnmon_area + offset,
1526                                    MEMTXATTRS_UNSPECIFIED,
1527                                    NULL);
1528         count++;
1529         address_space_stw(&address_space_memory,
1530                           channel_subsys.chnmon_area + offset, count,
1531                           MEMTXATTRS_UNSPECIFIED, NULL);
1532     }
1533 }
1534 
1535 IOInstEnding css_do_ssch(SubchDev *sch, ORB *orb)
1536 {
1537     SCSW *s = &sch->curr_status.scsw;
1538     PMCW *p = &sch->curr_status.pmcw;
1539 
1540     if (~(p->flags) & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA)) {
1541         return IOINST_CC_NOT_OPERATIONAL;
1542     }
1543 
1544     if (s->ctrl & SCSW_STCTL_STATUS_PEND) {
1545         return IOINST_CC_STATUS_PRESENT;
1546     }
1547 
1548     if (s->ctrl & (SCSW_FCTL_START_FUNC |
1549                    SCSW_FCTL_HALT_FUNC |
1550                    SCSW_FCTL_CLEAR_FUNC)) {
1551         return IOINST_CC_BUSY;
1552     }
1553 
1554     /* If monitoring is active, update counter. */
1555     if (channel_subsys.chnmon_active) {
1556         css_update_chnmon(sch);
1557     }
1558     sch->orb = *orb;
1559     sch->channel_prog = orb->cpa;
1560     /* Trigger the start function. */
1561     s->ctrl |= (SCSW_FCTL_START_FUNC | SCSW_ACTL_START_PEND);
1562     s->flags &= ~SCSW_FLAGS_MASK_PNO;
1563 
1564     return do_subchannel_work(sch);
1565 }
1566 
1567 static void copy_irb_to_guest(IRB *dest, const IRB *src, PMCW *pmcw,
1568                               int *irb_len)
1569 {
1570     int i;
1571     uint16_t stctl = src->scsw.ctrl & SCSW_CTRL_MASK_STCTL;
1572     uint16_t actl = src->scsw.ctrl & SCSW_CTRL_MASK_ACTL;
1573 
1574     copy_scsw_to_guest(&dest->scsw, &src->scsw);
1575 
1576     for (i = 0; i < ARRAY_SIZE(dest->esw); i++) {
1577         dest->esw[i] = cpu_to_be32(src->esw[i]);
1578     }
1579     for (i = 0; i < ARRAY_SIZE(dest->ecw); i++) {
1580         dest->ecw[i] = cpu_to_be32(src->ecw[i]);
1581     }
1582     *irb_len = sizeof(*dest) - sizeof(dest->emw);
1583 
1584     /* extended measurements enabled? */
1585     if ((src->scsw.flags & SCSW_FLAGS_MASK_ESWF) ||
1586         !(pmcw->flags & PMCW_FLAGS_MASK_TF) ||
1587         !(pmcw->chars & PMCW_CHARS_MASK_XMWME)) {
1588         return;
1589     }
1590     /* extended measurements pending? */
1591     if (!(stctl & SCSW_STCTL_STATUS_PEND)) {
1592         return;
1593     }
1594     if ((stctl & SCSW_STCTL_PRIMARY) ||
1595         (stctl == SCSW_STCTL_SECONDARY) ||
1596         ((stctl & SCSW_STCTL_INTERMEDIATE) && (actl & SCSW_ACTL_SUSP))) {
1597         for (i = 0; i < ARRAY_SIZE(dest->emw); i++) {
1598             dest->emw[i] = cpu_to_be32(src->emw[i]);
1599         }
1600     }
1601     *irb_len = sizeof(*dest);
1602 }
1603 
1604 int css_do_tsch_get_irb(SubchDev *sch, IRB *target_irb, int *irb_len)
1605 {
1606     SCSW *s = &sch->curr_status.scsw;
1607     PMCW *p = &sch->curr_status.pmcw;
1608     uint16_t stctl;
1609     IRB irb;
1610 
1611     if (~(p->flags) & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA)) {
1612         return 3;
1613     }
1614 
1615     stctl = s->ctrl & SCSW_CTRL_MASK_STCTL;
1616 
1617     /* Prepare the irb for the guest. */
1618     memset(&irb, 0, sizeof(IRB));
1619 
1620     /* Copy scsw from current status. */
1621     memcpy(&irb.scsw, s, sizeof(SCSW));
1622     if (stctl & SCSW_STCTL_STATUS_PEND) {
1623         if (s->cstat & (SCSW_CSTAT_DATA_CHECK |
1624                         SCSW_CSTAT_CHN_CTRL_CHK |
1625                         SCSW_CSTAT_INTF_CTRL_CHK)) {
1626             irb.scsw.flags |= SCSW_FLAGS_MASK_ESWF;
1627             irb.esw[0] = 0x04804000;
1628         } else {
1629             irb.esw[0] = 0x00800000;
1630         }
1631         /* If a unit check is pending, copy sense data. */
1632         if ((s->dstat & SCSW_DSTAT_UNIT_CHECK) &&
1633             (p->chars & PMCW_CHARS_MASK_CSENSE)) {
1634             int i;
1635 
1636             irb.scsw.flags |= SCSW_FLAGS_MASK_ESWF | SCSW_FLAGS_MASK_ECTL;
1637             /* Attention: sense_data is already BE! */
1638             memcpy(irb.ecw, sch->sense_data, sizeof(sch->sense_data));
1639             for (i = 0; i < ARRAY_SIZE(irb.ecw); i++) {
1640                 irb.ecw[i] = be32_to_cpu(irb.ecw[i]);
1641             }
1642             irb.esw[1] = 0x01000000 | (sizeof(sch->sense_data) << 8);
1643         }
1644     }
1645     /* Store the irb to the guest. */
1646     copy_irb_to_guest(target_irb, &irb, p, irb_len);
1647 
1648     return ((stctl & SCSW_STCTL_STATUS_PEND) == 0);
1649 }
1650 
1651 void css_do_tsch_update_subch(SubchDev *sch)
1652 {
1653     SCSW *s = &sch->curr_status.scsw;
1654     PMCW *p = &sch->curr_status.pmcw;
1655     uint16_t stctl;
1656     uint16_t fctl;
1657     uint16_t actl;
1658 
1659     stctl = s->ctrl & SCSW_CTRL_MASK_STCTL;
1660     fctl = s->ctrl & SCSW_CTRL_MASK_FCTL;
1661     actl = s->ctrl & SCSW_CTRL_MASK_ACTL;
1662 
1663     /* Clear conditions on subchannel, if applicable. */
1664     if (stctl & SCSW_STCTL_STATUS_PEND) {
1665         s->ctrl &= ~SCSW_CTRL_MASK_STCTL;
1666         if ((stctl != (SCSW_STCTL_INTERMEDIATE | SCSW_STCTL_STATUS_PEND)) ||
1667             ((fctl & SCSW_FCTL_HALT_FUNC) &&
1668              (actl & SCSW_ACTL_SUSP))) {
1669             s->ctrl &= ~SCSW_CTRL_MASK_FCTL;
1670         }
1671         if (stctl != (SCSW_STCTL_INTERMEDIATE | SCSW_STCTL_STATUS_PEND)) {
1672             s->flags &= ~SCSW_FLAGS_MASK_PNO;
1673             s->ctrl &= ~(SCSW_ACTL_RESUME_PEND |
1674                          SCSW_ACTL_START_PEND |
1675                          SCSW_ACTL_HALT_PEND |
1676                          SCSW_ACTL_CLEAR_PEND |
1677                          SCSW_ACTL_SUSP);
1678         } else {
1679             if ((actl & SCSW_ACTL_SUSP) &&
1680                 (fctl & SCSW_FCTL_START_FUNC)) {
1681                 s->flags &= ~SCSW_FLAGS_MASK_PNO;
1682                 if (fctl & SCSW_FCTL_HALT_FUNC) {
1683                     s->ctrl &= ~(SCSW_ACTL_RESUME_PEND |
1684                                  SCSW_ACTL_START_PEND |
1685                                  SCSW_ACTL_HALT_PEND |
1686                                  SCSW_ACTL_CLEAR_PEND |
1687                                  SCSW_ACTL_SUSP);
1688                 } else {
1689                     s->ctrl &= ~SCSW_ACTL_RESUME_PEND;
1690                 }
1691             }
1692         }
1693         /* Clear pending sense data. */
1694         if (p->chars & PMCW_CHARS_MASK_CSENSE) {
1695             memset(sch->sense_data, 0 , sizeof(sch->sense_data));
1696         }
1697     }
1698 }
1699 
1700 static void copy_crw_to_guest(CRW *dest, const CRW *src)
1701 {
1702     dest->flags = cpu_to_be16(src->flags);
1703     dest->rsid = cpu_to_be16(src->rsid);
1704 }
1705 
1706 int css_do_stcrw(CRW *crw)
1707 {
1708     CrwContainer *crw_cont;
1709     int ret;
1710 
1711     crw_cont = QTAILQ_FIRST(&channel_subsys.pending_crws);
1712     if (crw_cont) {
1713         QTAILQ_REMOVE(&channel_subsys.pending_crws, crw_cont, sibling);
1714         copy_crw_to_guest(crw, &crw_cont->crw);
1715         g_free(crw_cont);
1716         ret = 0;
1717     } else {
1718         /* List was empty, turn crw machine checks on again. */
1719         memset(crw, 0, sizeof(*crw));
1720         channel_subsys.do_crw_mchk = true;
1721         ret = 1;
1722     }
1723 
1724     return ret;
1725 }
1726 
1727 static void copy_crw_from_guest(CRW *dest, const CRW *src)
1728 {
1729     dest->flags = be16_to_cpu(src->flags);
1730     dest->rsid = be16_to_cpu(src->rsid);
1731 }
1732 
1733 void css_undo_stcrw(CRW *crw)
1734 {
1735     CrwContainer *crw_cont;
1736 
1737     crw_cont = g_try_new0(CrwContainer, 1);
1738     if (!crw_cont) {
1739         channel_subsys.crws_lost = true;
1740         return;
1741     }
1742     copy_crw_from_guest(&crw_cont->crw, crw);
1743 
1744     QTAILQ_INSERT_HEAD(&channel_subsys.pending_crws, crw_cont, sibling);
1745 }
1746 
1747 int css_collect_chp_desc(int m, uint8_t cssid, uint8_t f_chpid, uint8_t l_chpid,
1748                          int rfmt, void *buf)
1749 {
1750     int i, desc_size;
1751     uint32_t words[8];
1752     uint32_t chpid_type_word;
1753     CssImage *css;
1754 
1755     if (!m && !cssid) {
1756         css = channel_subsys.css[channel_subsys.default_cssid];
1757     } else {
1758         css = channel_subsys.css[cssid];
1759     }
1760     if (!css) {
1761         return 0;
1762     }
1763     desc_size = 0;
1764     for (i = f_chpid; i <= l_chpid; i++) {
1765         if (css->chpids[i].in_use) {
1766             chpid_type_word = 0x80000000 | (css->chpids[i].type << 8) | i;
1767             if (rfmt == 0) {
1768                 words[0] = cpu_to_be32(chpid_type_word);
1769                 words[1] = 0;
1770                 memcpy(buf + desc_size, words, 8);
1771                 desc_size += 8;
1772             } else if (rfmt == 1) {
1773                 words[0] = cpu_to_be32(chpid_type_word);
1774                 words[1] = 0;
1775                 words[2] = 0;
1776                 words[3] = 0;
1777                 words[4] = 0;
1778                 words[5] = 0;
1779                 words[6] = 0;
1780                 words[7] = 0;
1781                 memcpy(buf + desc_size, words, 32);
1782                 desc_size += 32;
1783             }
1784         }
1785     }
1786     return desc_size;
1787 }
1788 
1789 void css_do_schm(uint8_t mbk, int update, int dct, uint64_t mbo)
1790 {
1791     /* dct is currently ignored (not really meaningful for our devices) */
1792     /* TODO: Don't ignore mbk. */
1793     if (update && !channel_subsys.chnmon_active) {
1794         /* Enable measuring. */
1795         channel_subsys.chnmon_area = mbo;
1796         channel_subsys.chnmon_active = true;
1797     }
1798     if (!update && channel_subsys.chnmon_active) {
1799         /* Disable measuring. */
1800         channel_subsys.chnmon_area = 0;
1801         channel_subsys.chnmon_active = false;
1802     }
1803 }
1804 
1805 IOInstEnding css_do_rsch(SubchDev *sch)
1806 {
1807     SCSW *s = &sch->curr_status.scsw;
1808     PMCW *p = &sch->curr_status.pmcw;
1809 
1810     if (~(p->flags) & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA)) {
1811         return IOINST_CC_NOT_OPERATIONAL;
1812     }
1813 
1814     if (s->ctrl & SCSW_STCTL_STATUS_PEND) {
1815         return IOINST_CC_STATUS_PRESENT;
1816     }
1817 
1818     if (((s->ctrl & SCSW_CTRL_MASK_FCTL) != SCSW_FCTL_START_FUNC) ||
1819         (s->ctrl & SCSW_ACTL_RESUME_PEND) ||
1820         (!(s->ctrl & SCSW_ACTL_SUSP))) {
1821         return IOINST_CC_BUSY;
1822     }
1823 
1824     /* If monitoring is active, update counter. */
1825     if (channel_subsys.chnmon_active) {
1826         css_update_chnmon(sch);
1827     }
1828 
1829     s->ctrl |= SCSW_ACTL_RESUME_PEND;
1830     return do_subchannel_work(sch);
1831 }
1832 
1833 int css_do_rchp(uint8_t cssid, uint8_t chpid)
1834 {
1835     uint8_t real_cssid;
1836 
1837     if (cssid > channel_subsys.max_cssid) {
1838         return -EINVAL;
1839     }
1840     if (channel_subsys.max_cssid == 0) {
1841         real_cssid = channel_subsys.default_cssid;
1842     } else {
1843         real_cssid = cssid;
1844     }
1845     if (!channel_subsys.css[real_cssid]) {
1846         return -EINVAL;
1847     }
1848 
1849     if (!channel_subsys.css[real_cssid]->chpids[chpid].in_use) {
1850         return -ENODEV;
1851     }
1852 
1853     if (!channel_subsys.css[real_cssid]->chpids[chpid].is_virtual) {
1854         fprintf(stderr,
1855                 "rchp unsupported for non-virtual chpid %x.%02x!\n",
1856                 real_cssid, chpid);
1857         return -ENODEV;
1858     }
1859 
1860     /* We don't really use a channel path, so we're done here. */
1861     css_queue_crw(CRW_RSC_CHP, CRW_ERC_INIT, 1,
1862                   channel_subsys.max_cssid > 0 ? 1 : 0, chpid);
1863     if (channel_subsys.max_cssid > 0) {
1864         css_queue_crw(CRW_RSC_CHP, CRW_ERC_INIT, 1, 0, real_cssid << 8);
1865     }
1866     return 0;
1867 }
1868 
1869 bool css_schid_final(int m, uint8_t cssid, uint8_t ssid, uint16_t schid)
1870 {
1871     SubchSet *set;
1872     uint8_t real_cssid;
1873 
1874     real_cssid = (!m && (cssid == 0)) ? channel_subsys.default_cssid : cssid;
1875     if (ssid > MAX_SSID ||
1876         !channel_subsys.css[real_cssid] ||
1877         !channel_subsys.css[real_cssid]->sch_set[ssid]) {
1878         return true;
1879     }
1880     set = channel_subsys.css[real_cssid]->sch_set[ssid];
1881     return schid > find_last_bit(set->schids_used,
1882                                  (MAX_SCHID + 1) / sizeof(unsigned long));
1883 }
1884 
1885 unsigned int css_find_free_chpid(uint8_t cssid)
1886 {
1887     CssImage *css = channel_subsys.css[cssid];
1888     unsigned int chpid;
1889 
1890     if (!css) {
1891         return MAX_CHPID + 1;
1892     }
1893 
1894     for (chpid = 0; chpid <= MAX_CHPID; chpid++) {
1895         /* skip reserved chpid */
1896         if (chpid == VIRTIO_CCW_CHPID) {
1897             continue;
1898         }
1899         if (!css->chpids[chpid].in_use) {
1900             return chpid;
1901         }
1902     }
1903     return MAX_CHPID + 1;
1904 }
1905 
1906 static int css_add_chpid(uint8_t cssid, uint8_t chpid, uint8_t type,
1907                          bool is_virt)
1908 {
1909     CssImage *css;
1910 
1911     trace_css_chpid_add(cssid, chpid, type);
1912     css = channel_subsys.css[cssid];
1913     if (!css) {
1914         return -EINVAL;
1915     }
1916     if (css->chpids[chpid].in_use) {
1917         return -EEXIST;
1918     }
1919     css->chpids[chpid].in_use = 1;
1920     css->chpids[chpid].type = type;
1921     css->chpids[chpid].is_virtual = is_virt;
1922 
1923     css_generate_chp_crws(cssid, chpid);
1924 
1925     return 0;
1926 }
1927 
1928 void css_sch_build_virtual_schib(SubchDev *sch, uint8_t chpid, uint8_t type)
1929 {
1930     PMCW *p = &sch->curr_status.pmcw;
1931     SCSW *s = &sch->curr_status.scsw;
1932     int i;
1933     CssImage *css = channel_subsys.css[sch->cssid];
1934 
1935     assert(css != NULL);
1936     memset(p, 0, sizeof(PMCW));
1937     p->flags |= PMCW_FLAGS_MASK_DNV;
1938     p->devno = sch->devno;
1939     /* single path */
1940     p->pim = 0x80;
1941     p->pom = 0xff;
1942     p->pam = 0x80;
1943     p->chpid[0] = chpid;
1944     if (!css->chpids[chpid].in_use) {
1945         css_add_chpid(sch->cssid, chpid, type, true);
1946     }
1947 
1948     memset(s, 0, sizeof(SCSW));
1949     sch->curr_status.mba = 0;
1950     for (i = 0; i < ARRAY_SIZE(sch->curr_status.mda); i++) {
1951         sch->curr_status.mda[i] = 0;
1952     }
1953 }
1954 
1955 SubchDev *css_find_subch(uint8_t m, uint8_t cssid, uint8_t ssid, uint16_t schid)
1956 {
1957     uint8_t real_cssid;
1958 
1959     real_cssid = (!m && (cssid == 0)) ? channel_subsys.default_cssid : cssid;
1960 
1961     if (!channel_subsys.css[real_cssid]) {
1962         return NULL;
1963     }
1964 
1965     if (!channel_subsys.css[real_cssid]->sch_set[ssid]) {
1966         return NULL;
1967     }
1968 
1969     return channel_subsys.css[real_cssid]->sch_set[ssid]->sch[schid];
1970 }
1971 
1972 /**
1973  * Return free device number in subchannel set.
1974  *
1975  * Return index of the first free device number in the subchannel set
1976  * identified by @p cssid and @p ssid, beginning the search at @p
1977  * start and wrapping around at MAX_DEVNO. Return a value exceeding
1978  * MAX_SCHID if there are no free device numbers in the subchannel
1979  * set.
1980  */
1981 static uint32_t css_find_free_devno(uint8_t cssid, uint8_t ssid,
1982                                     uint16_t start)
1983 {
1984     uint32_t round;
1985 
1986     for (round = 0; round <= MAX_DEVNO; round++) {
1987         uint16_t devno = (start + round) % MAX_DEVNO;
1988 
1989         if (!css_devno_used(cssid, ssid, devno)) {
1990             return devno;
1991         }
1992     }
1993     return MAX_DEVNO + 1;
1994 }
1995 
1996 /**
1997  * Return first free subchannel (id) in subchannel set.
1998  *
1999  * Return index of the first free subchannel in the subchannel set
2000  * identified by @p cssid and @p ssid, if there is any. Return a value
2001  * exceeding MAX_SCHID if there are no free subchannels in the
2002  * subchannel set.
2003  */
2004 static uint32_t css_find_free_subch(uint8_t cssid, uint8_t ssid)
2005 {
2006     uint32_t schid;
2007 
2008     for (schid = 0; schid <= MAX_SCHID; schid++) {
2009         if (!css_find_subch(1, cssid, ssid, schid)) {
2010             return schid;
2011         }
2012     }
2013     return MAX_SCHID + 1;
2014 }
2015 
2016 /**
2017  * Return first free subchannel (id) in subchannel set for a device number
2018  *
2019  * Verify the device number @p devno is not used yet in the subchannel
2020  * set identified by @p cssid and @p ssid. Set @p schid to the index
2021  * of the first free subchannel in the subchannel set, if there is
2022  * any. Return true if everything succeeded and false otherwise.
2023  */
2024 static bool css_find_free_subch_for_devno(uint8_t cssid, uint8_t ssid,
2025                                           uint16_t devno, uint16_t *schid,
2026                                           Error **errp)
2027 {
2028     uint32_t free_schid;
2029 
2030     assert(schid);
2031     if (css_devno_used(cssid, ssid, devno)) {
2032         error_setg(errp, "Device %x.%x.%04x already exists",
2033                    cssid, ssid, devno);
2034         return false;
2035     }
2036     free_schid = css_find_free_subch(cssid, ssid);
2037     if (free_schid > MAX_SCHID) {
2038         error_setg(errp, "No free subchannel found for %x.%x.%04x",
2039                    cssid, ssid, devno);
2040         return false;
2041     }
2042     *schid = free_schid;
2043     return true;
2044 }
2045 
2046 /**
2047  * Return first free subchannel (id) and device number
2048  *
2049  * Locate the first free subchannel and first free device number in
2050  * any of the subchannel sets of the channel subsystem identified by
2051  * @p cssid. Return false if no free subchannel / device number could
2052  * be found. Otherwise set @p ssid, @p devno and @p schid to identify
2053  * the available subchannel and device number and return true.
2054  *
2055  * May modify @p ssid, @p devno and / or @p schid even if no free
2056  * subchannel / device number could be found.
2057  */
2058 static bool css_find_free_subch_and_devno(uint8_t cssid, uint8_t *ssid,
2059                                           uint16_t *devno, uint16_t *schid,
2060                                           Error **errp)
2061 {
2062     uint32_t free_schid, free_devno;
2063 
2064     assert(ssid && devno && schid);
2065     for (*ssid = 0; *ssid <= MAX_SSID; (*ssid)++) {
2066         free_schid = css_find_free_subch(cssid, *ssid);
2067         if (free_schid > MAX_SCHID) {
2068             continue;
2069         }
2070         free_devno = css_find_free_devno(cssid, *ssid, free_schid);
2071         if (free_devno > MAX_DEVNO) {
2072             continue;
2073         }
2074         *schid = free_schid;
2075         *devno = free_devno;
2076         return true;
2077     }
2078     error_setg(errp, "Virtual channel subsystem is full!");
2079     return false;
2080 }
2081 
2082 bool css_subch_visible(SubchDev *sch)
2083 {
2084     if (sch->ssid > channel_subsys.max_ssid) {
2085         return false;
2086     }
2087 
2088     if (sch->cssid != channel_subsys.default_cssid) {
2089         return (channel_subsys.max_cssid > 0);
2090     }
2091 
2092     return true;
2093 }
2094 
2095 bool css_present(uint8_t cssid)
2096 {
2097     return (channel_subsys.css[cssid] != NULL);
2098 }
2099 
2100 bool css_devno_used(uint8_t cssid, uint8_t ssid, uint16_t devno)
2101 {
2102     if (!channel_subsys.css[cssid]) {
2103         return false;
2104     }
2105     if (!channel_subsys.css[cssid]->sch_set[ssid]) {
2106         return false;
2107     }
2108 
2109     return !!test_bit(devno,
2110                       channel_subsys.css[cssid]->sch_set[ssid]->devnos_used);
2111 }
2112 
2113 void css_subch_assign(uint8_t cssid, uint8_t ssid, uint16_t schid,
2114                       uint16_t devno, SubchDev *sch)
2115 {
2116     CssImage *css;
2117     SubchSet *s_set;
2118 
2119     trace_css_assign_subch(sch ? "assign" : "deassign", cssid, ssid, schid,
2120                            devno);
2121     if (!channel_subsys.css[cssid]) {
2122         fprintf(stderr,
2123                 "Suspicious call to %s (%x.%x.%04x) for non-existing css!\n",
2124                 __func__, cssid, ssid, schid);
2125         return;
2126     }
2127     css = channel_subsys.css[cssid];
2128 
2129     if (!css->sch_set[ssid]) {
2130         css->sch_set[ssid] = g_new0(SubchSet, 1);
2131     }
2132     s_set = css->sch_set[ssid];
2133 
2134     s_set->sch[schid] = sch;
2135     if (sch) {
2136         set_bit(schid, s_set->schids_used);
2137         set_bit(devno, s_set->devnos_used);
2138     } else {
2139         clear_bit(schid, s_set->schids_used);
2140         clear_bit(devno, s_set->devnos_used);
2141     }
2142 }
2143 
2144 void css_queue_crw(uint8_t rsc, uint8_t erc, int solicited,
2145                    int chain, uint16_t rsid)
2146 {
2147     CrwContainer *crw_cont;
2148 
2149     trace_css_crw(rsc, erc, rsid, chain ? "(chained)" : "");
2150     /* TODO: Maybe use a static crw pool? */
2151     crw_cont = g_try_new0(CrwContainer, 1);
2152     if (!crw_cont) {
2153         channel_subsys.crws_lost = true;
2154         return;
2155     }
2156     crw_cont->crw.flags = (rsc << 8) | erc;
2157     if (solicited) {
2158         crw_cont->crw.flags |= CRW_FLAGS_MASK_S;
2159     }
2160     if (chain) {
2161         crw_cont->crw.flags |= CRW_FLAGS_MASK_C;
2162     }
2163     crw_cont->crw.rsid = rsid;
2164     if (channel_subsys.crws_lost) {
2165         crw_cont->crw.flags |= CRW_FLAGS_MASK_R;
2166         channel_subsys.crws_lost = false;
2167     }
2168 
2169     QTAILQ_INSERT_TAIL(&channel_subsys.pending_crws, crw_cont, sibling);
2170 
2171     if (channel_subsys.do_crw_mchk) {
2172         channel_subsys.do_crw_mchk = false;
2173         /* Inject crw pending machine check. */
2174         s390_crw_mchk();
2175     }
2176 }
2177 
2178 void css_generate_sch_crws(uint8_t cssid, uint8_t ssid, uint16_t schid,
2179                            int hotplugged, int add)
2180 {
2181     uint8_t guest_cssid;
2182     bool chain_crw;
2183 
2184     if (add && !hotplugged) {
2185         return;
2186     }
2187     if (channel_subsys.max_cssid == 0) {
2188         /* Default cssid shows up as 0. */
2189         guest_cssid = (cssid == channel_subsys.default_cssid) ? 0 : cssid;
2190     } else {
2191         /* Show real cssid to the guest. */
2192         guest_cssid = cssid;
2193     }
2194     /*
2195      * Only notify for higher subchannel sets/channel subsystems if the
2196      * guest has enabled it.
2197      */
2198     if ((ssid > channel_subsys.max_ssid) ||
2199         (guest_cssid > channel_subsys.max_cssid) ||
2200         ((channel_subsys.max_cssid == 0) &&
2201          (cssid != channel_subsys.default_cssid))) {
2202         return;
2203     }
2204     chain_crw = (channel_subsys.max_ssid > 0) ||
2205             (channel_subsys.max_cssid > 0);
2206     css_queue_crw(CRW_RSC_SUBCH, CRW_ERC_IPI, 0, chain_crw ? 1 : 0, schid);
2207     if (chain_crw) {
2208         css_queue_crw(CRW_RSC_SUBCH, CRW_ERC_IPI, 0, 0,
2209                       (guest_cssid << 8) | (ssid << 4));
2210     }
2211     /* RW_ERC_IPI --> clear pending interrupts */
2212     css_clear_io_interrupt(css_do_build_subchannel_id(cssid, ssid), schid);
2213 }
2214 
2215 void css_generate_chp_crws(uint8_t cssid, uint8_t chpid)
2216 {
2217     /* TODO */
2218 }
2219 
2220 void css_generate_css_crws(uint8_t cssid)
2221 {
2222     if (!channel_subsys.sei_pending) {
2223         css_queue_crw(CRW_RSC_CSS, CRW_ERC_EVENT, 0, 0, cssid);
2224     }
2225     channel_subsys.sei_pending = true;
2226 }
2227 
2228 void css_clear_sei_pending(void)
2229 {
2230     channel_subsys.sei_pending = false;
2231 }
2232 
2233 int css_enable_mcsse(void)
2234 {
2235     trace_css_enable_facility("mcsse");
2236     channel_subsys.max_cssid = MAX_CSSID;
2237     return 0;
2238 }
2239 
2240 int css_enable_mss(void)
2241 {
2242     trace_css_enable_facility("mss");
2243     channel_subsys.max_ssid = MAX_SSID;
2244     return 0;
2245 }
2246 
2247 void css_reset_sch(SubchDev *sch)
2248 {
2249     PMCW *p = &sch->curr_status.pmcw;
2250 
2251     if ((p->flags & PMCW_FLAGS_MASK_ENA) != 0 && sch->disable_cb) {
2252         sch->disable_cb(sch);
2253     }
2254 
2255     p->intparm = 0;
2256     p->flags &= ~(PMCW_FLAGS_MASK_ISC | PMCW_FLAGS_MASK_ENA |
2257                   PMCW_FLAGS_MASK_LM | PMCW_FLAGS_MASK_MME |
2258                   PMCW_FLAGS_MASK_MP | PMCW_FLAGS_MASK_TF);
2259     p->flags |= PMCW_FLAGS_MASK_DNV;
2260     p->devno = sch->devno;
2261     p->pim = 0x80;
2262     p->lpm = p->pim;
2263     p->pnom = 0;
2264     p->lpum = 0;
2265     p->mbi = 0;
2266     p->pom = 0xff;
2267     p->pam = 0x80;
2268     p->chars &= ~(PMCW_CHARS_MASK_MBFC | PMCW_CHARS_MASK_XMWME |
2269                   PMCW_CHARS_MASK_CSENSE);
2270 
2271     memset(&sch->curr_status.scsw, 0, sizeof(sch->curr_status.scsw));
2272     sch->curr_status.mba = 0;
2273 
2274     sch->channel_prog = 0x0;
2275     sch->last_cmd_valid = false;
2276     sch->thinint_active = false;
2277 }
2278 
2279 void css_reset(void)
2280 {
2281     CrwContainer *crw_cont;
2282 
2283     /* Clean up monitoring. */
2284     channel_subsys.chnmon_active = false;
2285     channel_subsys.chnmon_area = 0;
2286 
2287     /* Clear pending CRWs. */
2288     while ((crw_cont = QTAILQ_FIRST(&channel_subsys.pending_crws))) {
2289         QTAILQ_REMOVE(&channel_subsys.pending_crws, crw_cont, sibling);
2290         g_free(crw_cont);
2291     }
2292     channel_subsys.sei_pending = false;
2293     channel_subsys.do_crw_mchk = true;
2294     channel_subsys.crws_lost = false;
2295 
2296     /* Reset maximum ids. */
2297     channel_subsys.max_cssid = 0;
2298     channel_subsys.max_ssid = 0;
2299 }
2300 
2301 static void get_css_devid(Object *obj, Visitor *v, const char *name,
2302                           void *opaque, Error **errp)
2303 {
2304     DeviceState *dev = DEVICE(obj);
2305     Property *prop = opaque;
2306     CssDevId *dev_id = qdev_get_prop_ptr(dev, prop);
2307     char buffer[] = "xx.x.xxxx";
2308     char *p = buffer;
2309     int r;
2310 
2311     if (dev_id->valid) {
2312 
2313         r = snprintf(buffer, sizeof(buffer), "%02x.%1x.%04x", dev_id->cssid,
2314                      dev_id->ssid, dev_id->devid);
2315         assert(r == sizeof(buffer) - 1);
2316 
2317         /* drop leading zero */
2318         if (dev_id->cssid <= 0xf) {
2319             p++;
2320         }
2321     } else {
2322         snprintf(buffer, sizeof(buffer), "<unset>");
2323     }
2324 
2325     visit_type_str(v, name, &p, errp);
2326 }
2327 
2328 /*
2329  * parse <cssid>.<ssid>.<devid> and assert valid range for cssid/ssid
2330  */
2331 static void set_css_devid(Object *obj, Visitor *v, const char *name,
2332                           void *opaque, Error **errp)
2333 {
2334     DeviceState *dev = DEVICE(obj);
2335     Property *prop = opaque;
2336     CssDevId *dev_id = qdev_get_prop_ptr(dev, prop);
2337     Error *local_err = NULL;
2338     char *str;
2339     int num, n1, n2;
2340     unsigned int cssid, ssid, devid;
2341 
2342     if (dev->realized) {
2343         qdev_prop_set_after_realize(dev, name, errp);
2344         return;
2345     }
2346 
2347     visit_type_str(v, name, &str, &local_err);
2348     if (local_err) {
2349         error_propagate(errp, local_err);
2350         return;
2351     }
2352 
2353     num = sscanf(str, "%2x.%1x%n.%4x%n", &cssid, &ssid, &n1, &devid, &n2);
2354     if (num != 3 || (n2 - n1) != 5 || strlen(str) != n2) {
2355         error_set_from_qdev_prop_error(errp, EINVAL, dev, prop, str);
2356         goto out;
2357     }
2358     if ((cssid > MAX_CSSID) || (ssid > MAX_SSID)) {
2359         error_setg(errp, "Invalid cssid or ssid: cssid %x, ssid %x",
2360                    cssid, ssid);
2361         goto out;
2362     }
2363 
2364     dev_id->cssid = cssid;
2365     dev_id->ssid = ssid;
2366     dev_id->devid = devid;
2367     dev_id->valid = true;
2368 
2369 out:
2370     g_free(str);
2371 }
2372 
2373 const PropertyInfo css_devid_propinfo = {
2374     .name = "str",
2375     .description = "Identifier of an I/O device in the channel "
2376                    "subsystem, example: fe.1.23ab",
2377     .get = get_css_devid,
2378     .set = set_css_devid,
2379 };
2380 
2381 const PropertyInfo css_devid_ro_propinfo = {
2382     .name = "str",
2383     .description = "Read-only identifier of an I/O device in the channel "
2384                    "subsystem, example: fe.1.23ab",
2385     .get = get_css_devid,
2386 };
2387 
2388 SubchDev *css_create_sch(CssDevId bus_id, Error **errp)
2389 {
2390     uint16_t schid = 0;
2391     SubchDev *sch;
2392 
2393     if (bus_id.valid) {
2394         if (!channel_subsys.css[bus_id.cssid]) {
2395             css_create_css_image(bus_id.cssid, false);
2396         }
2397 
2398         if (!css_find_free_subch_for_devno(bus_id.cssid, bus_id.ssid,
2399                                            bus_id.devid, &schid, errp)) {
2400             return NULL;
2401         }
2402     } else {
2403         for (bus_id.cssid = channel_subsys.default_cssid;;) {
2404             if (!channel_subsys.css[bus_id.cssid]) {
2405                 css_create_css_image(bus_id.cssid, false);
2406             }
2407 
2408             if   (css_find_free_subch_and_devno(bus_id.cssid, &bus_id.ssid,
2409                                                 &bus_id.devid, &schid,
2410                                                 NULL)) {
2411                 break;
2412             }
2413             bus_id.cssid = (bus_id.cssid + 1) % MAX_CSSID;
2414             if (bus_id.cssid == channel_subsys.default_cssid) {
2415                 error_setg(errp, "Virtual channel subsystem is full!");
2416                 return NULL;
2417             }
2418         }
2419     }
2420 
2421     sch = g_new0(SubchDev, 1);
2422     sch->cssid = bus_id.cssid;
2423     sch->ssid = bus_id.ssid;
2424     sch->devno = bus_id.devid;
2425     sch->schid = schid;
2426     css_subch_assign(sch->cssid, sch->ssid, schid, sch->devno, sch);
2427     return sch;
2428 }
2429 
2430 static int css_sch_get_chpids(SubchDev *sch, CssDevId *dev_id)
2431 {
2432     char *fid_path;
2433     FILE *fd;
2434     uint32_t chpid[8];
2435     int i;
2436     PMCW *p = &sch->curr_status.pmcw;
2437 
2438     fid_path = g_strdup_printf("/sys/bus/css/devices/%x.%x.%04x/chpids",
2439                                dev_id->cssid, dev_id->ssid, dev_id->devid);
2440     fd = fopen(fid_path, "r");
2441     if (fd == NULL) {
2442         error_report("%s: open %s failed", __func__, fid_path);
2443         g_free(fid_path);
2444         return -EINVAL;
2445     }
2446 
2447     if (fscanf(fd, "%x %x %x %x %x %x %x %x",
2448         &chpid[0], &chpid[1], &chpid[2], &chpid[3],
2449         &chpid[4], &chpid[5], &chpid[6], &chpid[7]) != 8) {
2450         fclose(fd);
2451         g_free(fid_path);
2452         return -EINVAL;
2453     }
2454 
2455     for (i = 0; i < ARRAY_SIZE(p->chpid); i++) {
2456         p->chpid[i] = chpid[i];
2457     }
2458 
2459     fclose(fd);
2460     g_free(fid_path);
2461 
2462     return 0;
2463 }
2464 
2465 static int css_sch_get_path_masks(SubchDev *sch, CssDevId *dev_id)
2466 {
2467     char *fid_path;
2468     FILE *fd;
2469     uint32_t pim, pam, pom;
2470     PMCW *p = &sch->curr_status.pmcw;
2471 
2472     fid_path = g_strdup_printf("/sys/bus/css/devices/%x.%x.%04x/pimpampom",
2473                                dev_id->cssid, dev_id->ssid, dev_id->devid);
2474     fd = fopen(fid_path, "r");
2475     if (fd == NULL) {
2476         error_report("%s: open %s failed", __func__, fid_path);
2477         g_free(fid_path);
2478         return -EINVAL;
2479     }
2480 
2481     if (fscanf(fd, "%x %x %x", &pim, &pam, &pom) != 3) {
2482         fclose(fd);
2483         g_free(fid_path);
2484         return -EINVAL;
2485     }
2486 
2487     p->pim = pim;
2488     p->pam = pam;
2489     p->pom = pom;
2490     fclose(fd);
2491     g_free(fid_path);
2492 
2493     return 0;
2494 }
2495 
2496 static int css_sch_get_chpid_type(uint8_t chpid, uint32_t *type,
2497                                   CssDevId *dev_id)
2498 {
2499     char *fid_path;
2500     FILE *fd;
2501 
2502     fid_path = g_strdup_printf("/sys/devices/css%x/chp0.%02x/type",
2503                                dev_id->cssid, chpid);
2504     fd = fopen(fid_path, "r");
2505     if (fd == NULL) {
2506         error_report("%s: open %s failed", __func__, fid_path);
2507         g_free(fid_path);
2508         return -EINVAL;
2509     }
2510 
2511     if (fscanf(fd, "%x", type) != 1) {
2512         fclose(fd);
2513         g_free(fid_path);
2514         return -EINVAL;
2515     }
2516 
2517     fclose(fd);
2518     g_free(fid_path);
2519 
2520     return 0;
2521 }
2522 
2523 /*
2524  * We currently retrieve the real device information from sysfs to build the
2525  * guest subchannel information block without considering the migration feature.
2526  * We need to revisit this problem when we want to add migration support.
2527  */
2528 int css_sch_build_schib(SubchDev *sch, CssDevId *dev_id)
2529 {
2530     CssImage *css = channel_subsys.css[sch->cssid];
2531     PMCW *p = &sch->curr_status.pmcw;
2532     SCSW *s = &sch->curr_status.scsw;
2533     uint32_t type;
2534     int i, ret;
2535 
2536     assert(css != NULL);
2537     memset(p, 0, sizeof(PMCW));
2538     p->flags |= PMCW_FLAGS_MASK_DNV;
2539     /* We are dealing with I/O subchannels only. */
2540     p->devno = sch->devno;
2541 
2542     /* Grab path mask from sysfs. */
2543     ret = css_sch_get_path_masks(sch, dev_id);
2544     if (ret) {
2545         return ret;
2546     }
2547 
2548     /* Grab chpids from sysfs. */
2549     ret = css_sch_get_chpids(sch, dev_id);
2550     if (ret) {
2551         return ret;
2552     }
2553 
2554    /* Build chpid type. */
2555     for (i = 0; i < ARRAY_SIZE(p->chpid); i++) {
2556         if (p->chpid[i] && !css->chpids[p->chpid[i]].in_use) {
2557             ret = css_sch_get_chpid_type(p->chpid[i], &type, dev_id);
2558             if (ret) {
2559                 return ret;
2560             }
2561             css_add_chpid(sch->cssid, p->chpid[i], type, false);
2562         }
2563     }
2564 
2565     memset(s, 0, sizeof(SCSW));
2566     sch->curr_status.mba = 0;
2567     for (i = 0; i < ARRAY_SIZE(sch->curr_status.mda); i++) {
2568         sch->curr_status.mda[i] = 0;
2569     }
2570 
2571     return 0;
2572 }
2573