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