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