1 /*-
2 * Common functions for CAM "type" (peripheral) drivers.
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 *
6 * Copyright (c) 1997, 1998 Justin T. Gibbs.
7 * Copyright (c) 1997, 1998, 1999, 2000 Kenneth D. Merry.
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions, and the following disclaimer,
15 * without modification, immediately at the beginning of the file.
16 * 2. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
23 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/types.h>
36 #include <sys/malloc.h>
37 #include <sys/kernel.h>
38 #include <sys/bio.h>
39 #include <sys/conf.h>
40 #include <sys/devctl.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/buf.h>
44 #include <sys/proc.h>
45 #include <sys/devicestat.h>
46 #include <sys/sbuf.h>
47 #include <sys/sysctl.h>
48 #include <vm/vm.h>
49 #include <vm/vm_extern.h>
50
51 #include <cam/cam.h>
52 #include <cam/cam_ccb.h>
53 #include <cam/cam_compat.h>
54 #include <cam/cam_queue.h>
55 #include <cam/cam_xpt_periph.h>
56 #include <cam/cam_xpt_internal.h>
57 #include <cam/cam_periph.h>
58 #include <cam/cam_debug.h>
59 #include <cam/cam_sim.h>
60
61 #include <cam/scsi/scsi_all.h>
62 #include <cam/scsi/scsi_message.h>
63 #include <cam/scsi/scsi_pass.h>
64
65 static u_int camperiphnextunit(struct periph_driver *p_drv,
66 u_int newunit, bool wired,
67 path_id_t pathid, target_id_t target,
68 lun_id_t lun);
69 static u_int camperiphunit(struct periph_driver *p_drv,
70 path_id_t pathid, target_id_t target,
71 lun_id_t lun,
72 const char *sn);
73 static void camperiphdone(struct cam_periph *periph,
74 union ccb *done_ccb);
75 static void camperiphfree(struct cam_periph *periph);
76 static int camperiphscsistatuserror(union ccb *ccb,
77 union ccb **orig_ccb,
78 cam_flags camflags,
79 uint32_t sense_flags,
80 int *openings,
81 uint32_t *relsim_flags,
82 uint32_t *timeout,
83 uint32_t *action,
84 const char **action_string);
85 static int camperiphscsisenseerror(union ccb *ccb,
86 union ccb **orig_ccb,
87 cam_flags camflags,
88 uint32_t sense_flags,
89 int *openings,
90 uint32_t *relsim_flags,
91 uint32_t *timeout,
92 uint32_t *action,
93 const char **action_string);
94 static void cam_periph_devctl_notify(union ccb *ccb);
95
96 static int nperiph_drivers;
97 static int initialized = 0;
98 struct periph_driver **periph_drivers;
99
100 static MALLOC_DEFINE(M_CAMPERIPH, "CAM periph", "CAM peripheral buffers");
101
102 static int periph_selto_delay = 1000;
103 TUNABLE_INT("kern.cam.periph_selto_delay", &periph_selto_delay);
104 static int periph_noresrc_delay = 500;
105 TUNABLE_INT("kern.cam.periph_noresrc_delay", &periph_noresrc_delay);
106 static int periph_busy_delay = 500;
107 TUNABLE_INT("kern.cam.periph_busy_delay", &periph_busy_delay);
108
109 static u_int periph_mapmem_thresh = 65536;
110 SYSCTL_UINT(_kern_cam, OID_AUTO, mapmem_thresh, CTLFLAG_RWTUN,
111 &periph_mapmem_thresh, 0, "Threshold for user-space buffer mapping");
112
113 void
periphdriver_register(void * data)114 periphdriver_register(void *data)
115 {
116 struct periph_driver *drv = (struct periph_driver *)data;
117 struct periph_driver **newdrivers, **old;
118 int ndrivers;
119
120 again:
121 ndrivers = nperiph_drivers + 2;
122 newdrivers = malloc(sizeof(*newdrivers) * ndrivers, M_CAMPERIPH,
123 M_WAITOK);
124 xpt_lock_buses();
125 if (ndrivers != nperiph_drivers + 2) {
126 /*
127 * Lost race against itself; go around.
128 */
129 xpt_unlock_buses();
130 free(newdrivers, M_CAMPERIPH);
131 goto again;
132 }
133 if (periph_drivers)
134 bcopy(periph_drivers, newdrivers,
135 sizeof(*newdrivers) * nperiph_drivers);
136 newdrivers[nperiph_drivers] = drv;
137 newdrivers[nperiph_drivers + 1] = NULL;
138 old = periph_drivers;
139 periph_drivers = newdrivers;
140 nperiph_drivers++;
141 xpt_unlock_buses();
142 if (old)
143 free(old, M_CAMPERIPH);
144 /* If driver marked as early or it is late now, initialize it. */
145 if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
146 initialized > 1)
147 (*drv->init)();
148 }
149
150 int
periphdriver_unregister(void * data)151 periphdriver_unregister(void *data)
152 {
153 struct periph_driver *drv = (struct periph_driver *)data;
154 int error, n;
155
156 /* If driver marked as early or it is late now, deinitialize it. */
157 if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
158 initialized > 1) {
159 if (drv->deinit == NULL) {
160 printf("CAM periph driver '%s' doesn't have deinit.\n",
161 drv->driver_name);
162 return (EOPNOTSUPP);
163 }
164 error = drv->deinit();
165 if (error != 0)
166 return (error);
167 }
168
169 xpt_lock_buses();
170 for (n = 0; n < nperiph_drivers && periph_drivers[n] != drv; n++)
171 ;
172 KASSERT(n < nperiph_drivers,
173 ("Periph driver '%s' was not registered", drv->driver_name));
174 for (; n + 1 < nperiph_drivers; n++)
175 periph_drivers[n] = periph_drivers[n + 1];
176 periph_drivers[n + 1] = NULL;
177 nperiph_drivers--;
178 xpt_unlock_buses();
179 return (0);
180 }
181
182 void
periphdriver_init(int level)183 periphdriver_init(int level)
184 {
185 int i, early;
186
187 initialized = max(initialized, level);
188 for (i = 0; periph_drivers[i] != NULL; i++) {
189 early = (periph_drivers[i]->flags & CAM_PERIPH_DRV_EARLY) ? 1 : 2;
190 if (early == initialized)
191 (*periph_drivers[i]->init)();
192 }
193 }
194
195 cam_status
cam_periph_alloc(periph_ctor_t * periph_ctor,periph_oninv_t * periph_oninvalidate,periph_dtor_t * periph_dtor,periph_start_t * periph_start,char * name,cam_periph_type type,struct cam_path * path,ac_callback_t * ac_callback,ac_code code,void * arg)196 cam_periph_alloc(periph_ctor_t *periph_ctor,
197 periph_oninv_t *periph_oninvalidate,
198 periph_dtor_t *periph_dtor, periph_start_t *periph_start,
199 char *name, cam_periph_type type, struct cam_path *path,
200 ac_callback_t *ac_callback, ac_code code, void *arg)
201 {
202 struct periph_driver **p_drv;
203 struct cam_sim *sim;
204 struct cam_periph *periph;
205 struct cam_periph *cur_periph;
206 path_id_t path_id;
207 target_id_t target_id;
208 lun_id_t lun_id;
209 cam_status status;
210 u_int init_level;
211
212 init_level = 0;
213 /*
214 * Handle Hot-Plug scenarios. If there is already a peripheral
215 * of our type assigned to this path, we are likely waiting for
216 * final close on an old, invalidated, peripheral. If this is
217 * the case, queue up a deferred call to the peripheral's async
218 * handler. If it looks like a mistaken re-allocation, complain.
219 */
220 if ((periph = cam_periph_find(path, name)) != NULL) {
221 if ((periph->flags & CAM_PERIPH_INVALID) != 0
222 && (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) == 0) {
223 periph->flags |= CAM_PERIPH_NEW_DEV_FOUND;
224 periph->deferred_callback = ac_callback;
225 periph->deferred_ac = code;
226 return (CAM_REQ_INPROG);
227 } else {
228 printf("cam_periph_alloc: attempt to re-allocate "
229 "valid device %s%d rejected flags %#x "
230 "refcount %d\n", periph->periph_name,
231 periph->unit_number, periph->flags,
232 periph->refcount);
233 }
234 return (CAM_REQ_INVALID);
235 }
236
237 periph = (struct cam_periph *)malloc(sizeof(*periph), M_CAMPERIPH,
238 M_NOWAIT|M_ZERO);
239
240 if (periph == NULL)
241 return (CAM_RESRC_UNAVAIL);
242
243 init_level++;
244
245 sim = xpt_path_sim(path);
246 path_id = xpt_path_path_id(path);
247 target_id = xpt_path_target_id(path);
248 lun_id = xpt_path_lun_id(path);
249 periph->periph_start = periph_start;
250 periph->periph_dtor = periph_dtor;
251 periph->periph_oninval = periph_oninvalidate;
252 periph->type = type;
253 periph->periph_name = name;
254 periph->scheduled_priority = CAM_PRIORITY_NONE;
255 periph->immediate_priority = CAM_PRIORITY_NONE;
256 periph->refcount = 1; /* Dropped by invalidation. */
257 periph->sim = sim;
258 SLIST_INIT(&periph->ccb_list);
259 status = xpt_create_path(&path, periph, path_id, target_id, lun_id);
260 if (status != CAM_REQ_CMP)
261 goto failure;
262 periph->path = path;
263
264 xpt_lock_buses();
265 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
266 if (strcmp((*p_drv)->driver_name, name) == 0)
267 break;
268 }
269 if (*p_drv == NULL) {
270 printf("cam_periph_alloc: invalid periph name '%s'\n", name);
271 xpt_unlock_buses();
272 xpt_free_path(periph->path);
273 free(periph, M_CAMPERIPH);
274 return (CAM_REQ_INVALID);
275 }
276 periph->unit_number = camperiphunit(*p_drv, path_id, target_id, lun_id,
277 path->device->serial_num);
278 cur_periph = TAILQ_FIRST(&(*p_drv)->units);
279 while (cur_periph != NULL
280 && cur_periph->unit_number < periph->unit_number)
281 cur_periph = TAILQ_NEXT(cur_periph, unit_links);
282 if (cur_periph != NULL) {
283 KASSERT(cur_periph->unit_number != periph->unit_number,
284 ("duplicate units on periph list"));
285 TAILQ_INSERT_BEFORE(cur_periph, periph, unit_links);
286 } else {
287 TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
288 (*p_drv)->generation++;
289 }
290 xpt_unlock_buses();
291
292 init_level++;
293
294 status = xpt_add_periph(periph);
295 if (status != CAM_REQ_CMP)
296 goto failure;
297
298 init_level++;
299 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph created\n"));
300
301 status = periph_ctor(periph, arg);
302
303 if (status == CAM_REQ_CMP)
304 init_level++;
305
306 failure:
307 switch (init_level) {
308 case 4:
309 /* Initialized successfully */
310 break;
311 case 3:
312 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
313 xpt_remove_periph(periph);
314 /* FALLTHROUGH */
315 case 2:
316 xpt_lock_buses();
317 TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
318 xpt_unlock_buses();
319 xpt_free_path(periph->path);
320 /* FALLTHROUGH */
321 case 1:
322 free(periph, M_CAMPERIPH);
323 /* FALLTHROUGH */
324 case 0:
325 /* No cleanup to perform. */
326 break;
327 default:
328 panic("%s: Unknown init level", __func__);
329 }
330 return(status);
331 }
332
333 /*
334 * Find a peripheral structure with the specified path, target, lun,
335 * and (optionally) type. If the name is NULL, this function will return
336 * the first peripheral driver that matches the specified path.
337 */
338 struct cam_periph *
cam_periph_find(struct cam_path * path,char * name)339 cam_periph_find(struct cam_path *path, char *name)
340 {
341 struct periph_driver **p_drv;
342 struct cam_periph *periph;
343
344 xpt_lock_buses();
345 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
346 if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
347 continue;
348
349 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
350 if (xpt_path_comp(periph->path, path) == 0) {
351 xpt_unlock_buses();
352 cam_periph_assert(periph, MA_OWNED);
353 return(periph);
354 }
355 }
356 if (name != NULL) {
357 xpt_unlock_buses();
358 return(NULL);
359 }
360 }
361 xpt_unlock_buses();
362 return(NULL);
363 }
364
365 /*
366 * Find peripheral driver instances attached to the specified path.
367 */
368 int
cam_periph_list(struct cam_path * path,struct sbuf * sb)369 cam_periph_list(struct cam_path *path, struct sbuf *sb)
370 {
371 struct sbuf local_sb;
372 struct periph_driver **p_drv;
373 struct cam_periph *periph;
374 int count;
375 int sbuf_alloc_len;
376
377 sbuf_alloc_len = 16;
378 retry:
379 sbuf_new(&local_sb, NULL, sbuf_alloc_len, SBUF_FIXEDLEN);
380 count = 0;
381 xpt_lock_buses();
382 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
383 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
384 if (xpt_path_comp(periph->path, path) != 0)
385 continue;
386
387 if (sbuf_len(&local_sb) != 0)
388 sbuf_cat(&local_sb, ",");
389
390 sbuf_printf(&local_sb, "%s%d", periph->periph_name,
391 periph->unit_number);
392
393 if (sbuf_error(&local_sb) == ENOMEM) {
394 sbuf_alloc_len *= 2;
395 xpt_unlock_buses();
396 sbuf_delete(&local_sb);
397 goto retry;
398 }
399 count++;
400 }
401 }
402 xpt_unlock_buses();
403 sbuf_finish(&local_sb);
404 if (sbuf_len(sb) != 0)
405 sbuf_cat(sb, ",");
406 sbuf_cat(sb, sbuf_data(&local_sb));
407 sbuf_delete(&local_sb);
408 return (count);
409 }
410
411 int
cam_periph_acquire(struct cam_periph * periph)412 cam_periph_acquire(struct cam_periph *periph)
413 {
414 int status;
415
416 if (periph == NULL)
417 return (EINVAL);
418
419 status = ENOENT;
420 xpt_lock_buses();
421 if ((periph->flags & CAM_PERIPH_INVALID) == 0) {
422 periph->refcount++;
423 status = 0;
424 }
425 xpt_unlock_buses();
426
427 return (status);
428 }
429
430 void
cam_periph_doacquire(struct cam_periph * periph)431 cam_periph_doacquire(struct cam_periph *periph)
432 {
433
434 xpt_lock_buses();
435 KASSERT(periph->refcount >= 1,
436 ("cam_periph_doacquire() with refcount == %d", periph->refcount));
437 periph->refcount++;
438 xpt_unlock_buses();
439 }
440
441 void
cam_periph_release_locked_buses(struct cam_periph * periph)442 cam_periph_release_locked_buses(struct cam_periph *periph)
443 {
444
445 cam_periph_assert(periph, MA_OWNED);
446 KASSERT(periph->refcount >= 1, ("periph->refcount >= 1"));
447 if (--periph->refcount == 0)
448 camperiphfree(periph);
449 }
450
451 void
cam_periph_release_locked(struct cam_periph * periph)452 cam_periph_release_locked(struct cam_periph *periph)
453 {
454
455 if (periph == NULL)
456 return;
457
458 xpt_lock_buses();
459 cam_periph_release_locked_buses(periph);
460 xpt_unlock_buses();
461 }
462
463 void
cam_periph_release(struct cam_periph * periph)464 cam_periph_release(struct cam_periph *periph)
465 {
466 struct mtx *mtx;
467
468 if (periph == NULL)
469 return;
470
471 cam_periph_assert(periph, MA_NOTOWNED);
472 mtx = cam_periph_mtx(periph);
473 mtx_lock(mtx);
474 cam_periph_release_locked(periph);
475 mtx_unlock(mtx);
476 }
477
478 /*
479 * hold/unhold act as mutual exclusion for sections of the code that
480 * need to sleep and want to make sure that other sections that
481 * will interfere are held off. This only protects exclusive sections
482 * from each other.
483 */
484 int
cam_periph_hold(struct cam_periph * periph,int priority)485 cam_periph_hold(struct cam_periph *periph, int priority)
486 {
487 int error;
488
489 /*
490 * Increment the reference count on the peripheral
491 * while we wait for our lock attempt to succeed
492 * to ensure the peripheral doesn't disappear out
493 * from user us while we sleep.
494 */
495
496 if (cam_periph_acquire(periph) != 0)
497 return (ENXIO);
498
499 cam_periph_assert(periph, MA_OWNED);
500 while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
501 periph->flags |= CAM_PERIPH_LOCK_WANTED;
502 if ((error = cam_periph_sleep(periph, periph, priority,
503 "caplck", 0)) != 0) {
504 cam_periph_release_locked(periph);
505 return (error);
506 }
507 if (periph->flags & CAM_PERIPH_INVALID) {
508 cam_periph_release_locked(periph);
509 return (ENXIO);
510 }
511 }
512
513 periph->flags |= CAM_PERIPH_LOCKED;
514 return (0);
515 }
516
517 void
cam_periph_unhold(struct cam_periph * periph)518 cam_periph_unhold(struct cam_periph *periph)
519 {
520
521 cam_periph_assert(periph, MA_OWNED);
522
523 periph->flags &= ~CAM_PERIPH_LOCKED;
524 if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
525 periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
526 wakeup(periph);
527 }
528
529 cam_periph_release_locked(periph);
530 }
531
532 void
cam_periph_hold_boot(struct cam_periph * periph)533 cam_periph_hold_boot(struct cam_periph *periph)
534 {
535
536 root_mount_hold_token(periph->periph_name, &periph->periph_rootmount);
537 }
538
539 void
cam_periph_release_boot(struct cam_periph * periph)540 cam_periph_release_boot(struct cam_periph *periph)
541 {
542
543 root_mount_rel(&periph->periph_rootmount);
544 }
545
546 /*
547 * Look for the next unit number that is not currently in use for this
548 * peripheral type starting at "newunit". Also exclude unit numbers that
549 * are reserved by for future "hardwiring" unless we already know that this
550 * is a potential wired device. Only assume that the device is "wired" the
551 * first time through the loop since after that we'll be looking at unit
552 * numbers that did not match a wiring entry.
553 */
554 static u_int
camperiphnextunit(struct periph_driver * p_drv,u_int newunit,bool wired,path_id_t pathid,target_id_t target,lun_id_t lun)555 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, bool wired,
556 path_id_t pathid, target_id_t target, lun_id_t lun)
557 {
558 struct cam_periph *periph;
559 char *periph_name;
560 int i, val, dunit, r;
561 const char *dname, *strval;
562
563 periph_name = p_drv->driver_name;
564 for (;;newunit++) {
565 for (periph = TAILQ_FIRST(&p_drv->units);
566 periph != NULL && periph->unit_number != newunit;
567 periph = TAILQ_NEXT(periph, unit_links))
568 ;
569
570 if (periph != NULL && periph->unit_number == newunit) {
571 if (wired) {
572 xpt_print(periph->path, "Duplicate Wired "
573 "Device entry!\n");
574 xpt_print(periph->path, "Second device (%s "
575 "device at scbus%d target %d lun %d) will "
576 "not be wired\n", periph_name, pathid,
577 target, lun);
578 wired = false;
579 }
580 continue;
581 }
582 if (wired)
583 break;
584
585 /*
586 * Don't allow the mere presence of any attributes of a device
587 * means that it is for a wired down entry. Instead, insist that
588 * one of the matching criteria from camperiphunit be present
589 * for the device.
590 */
591 i = 0;
592 dname = periph_name;
593 for (;;) {
594 r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
595 if (r != 0)
596 break;
597
598 if (newunit != dunit)
599 continue;
600 if (resource_string_value(dname, dunit, "sn", &strval) == 0 ||
601 resource_int_value(dname, dunit, "lun", &val) == 0 ||
602 resource_int_value(dname, dunit, "target", &val) == 0 ||
603 resource_string_value(dname, dunit, "at", &strval) == 0)
604 break;
605 }
606 if (r != 0)
607 break;
608 }
609 return (newunit);
610 }
611
612 static u_int
camperiphunit(struct periph_driver * p_drv,path_id_t pathid,target_id_t target,lun_id_t lun,const char * sn)613 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
614 target_id_t target, lun_id_t lun, const char *sn)
615 {
616 bool wired = false;
617 u_int unit;
618 int i, val, dunit;
619 const char *dname, *strval;
620 char pathbuf[32], *periph_name;
621
622 periph_name = p_drv->driver_name;
623 snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
624 unit = 0;
625 i = 0;
626 dname = periph_name;
627
628 for (wired = false; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
629 wired = false) {
630 if (resource_string_value(dname, dunit, "at", &strval) == 0) {
631 if (strcmp(strval, pathbuf) != 0)
632 continue;
633 wired = true;
634 }
635 if (resource_int_value(dname, dunit, "target", &val) == 0) {
636 if (val != target)
637 continue;
638 wired = true;
639 }
640 if (resource_int_value(dname, dunit, "lun", &val) == 0) {
641 if (val != lun)
642 continue;
643 wired = true;
644 }
645 if (resource_string_value(dname, dunit, "sn", &strval) == 0) {
646 if (sn == NULL || strcmp(strval, sn) != 0)
647 continue;
648 wired = true;
649 }
650 if (wired) {
651 unit = dunit;
652 break;
653 }
654 }
655
656 /*
657 * Either start from 0 looking for the next unit or from
658 * the unit number given in the resource config. This way,
659 * if we have wildcard matches, we don't return the same
660 * unit number twice.
661 */
662 unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
663
664 return (unit);
665 }
666
667 void
cam_periph_invalidate(struct cam_periph * periph)668 cam_periph_invalidate(struct cam_periph *periph)
669 {
670
671 cam_periph_assert(periph, MA_OWNED);
672 /*
673 * We only tear down the device the first time a peripheral is
674 * invalidated.
675 */
676 if ((periph->flags & CAM_PERIPH_INVALID) != 0)
677 return;
678
679 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph invalidated\n"));
680 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting) {
681 struct sbuf sb;
682 char buffer[160];
683
684 sbuf_new(&sb, buffer, 160, SBUF_FIXEDLEN);
685 xpt_denounce_periph_sbuf(periph, &sb);
686 sbuf_finish(&sb);
687 sbuf_putbuf(&sb);
688 }
689 periph->flags |= CAM_PERIPH_INVALID;
690 periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
691 if (periph->periph_oninval != NULL)
692 periph->periph_oninval(periph);
693 cam_periph_release_locked(periph);
694 }
695
696 static void
camperiphfree(struct cam_periph * periph)697 camperiphfree(struct cam_periph *periph)
698 {
699 struct periph_driver **p_drv;
700 struct periph_driver *drv;
701
702 cam_periph_assert(periph, MA_OWNED);
703 KASSERT(periph->periph_allocating == 0, ("%s%d: freed while allocating",
704 periph->periph_name, periph->unit_number));
705 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
706 if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
707 break;
708 }
709 if (*p_drv == NULL) {
710 printf("camperiphfree: attempt to free non-existant periph\n");
711 return;
712 }
713 /*
714 * Cache a pointer to the periph_driver structure. If a
715 * periph_driver is added or removed from the array (see
716 * periphdriver_register()) while we drop the toplogy lock
717 * below, p_drv may change. This doesn't protect against this
718 * particular periph_driver going away. That will require full
719 * reference counting in the periph_driver infrastructure.
720 */
721 drv = *p_drv;
722
723 /*
724 * We need to set this flag before dropping the topology lock, to
725 * let anyone who is traversing the list that this peripheral is
726 * about to be freed, and there will be no more reference count
727 * checks.
728 */
729 periph->flags |= CAM_PERIPH_FREE;
730
731 /*
732 * The peripheral destructor semantics dictate calling with only the
733 * SIM mutex held. Since it might sleep, it should not be called
734 * with the topology lock held.
735 */
736 xpt_unlock_buses();
737
738 /*
739 * We need to call the peripheral destructor prior to removing the
740 * peripheral from the list. Otherwise, we risk running into a
741 * scenario where the peripheral unit number may get reused
742 * (because it has been removed from the list), but some resources
743 * used by the peripheral are still hanging around. In particular,
744 * the devfs nodes used by some peripherals like the pass(4) driver
745 * aren't fully cleaned up until the destructor is run. If the
746 * unit number is reused before the devfs instance is fully gone,
747 * devfs will panic.
748 */
749 if (periph->periph_dtor != NULL)
750 periph->periph_dtor(periph);
751
752 /*
753 * The peripheral list is protected by the topology lock. We have to
754 * remove the periph from the drv list before we call deferred_ac. The
755 * AC_FOUND_DEVICE callback won't create a new periph if it's still there.
756 */
757 xpt_lock_buses();
758
759 TAILQ_REMOVE(&drv->units, periph, unit_links);
760 drv->generation++;
761
762 xpt_remove_periph(periph);
763
764 xpt_unlock_buses();
765 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting)
766 xpt_print(periph->path, "Periph destroyed\n");
767 else
768 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
769
770 if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
771 union ccb ccb;
772 void *arg;
773
774 memset(&ccb, 0, sizeof(ccb));
775 switch (periph->deferred_ac) {
776 case AC_FOUND_DEVICE:
777 ccb.ccb_h.func_code = XPT_GDEV_TYPE;
778 xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
779 xpt_action(&ccb);
780 arg = &ccb;
781 break;
782 case AC_PATH_REGISTERED:
783 xpt_path_inq(&ccb.cpi, periph->path);
784 arg = &ccb;
785 break;
786 default:
787 arg = NULL;
788 break;
789 }
790 periph->deferred_callback(NULL, periph->deferred_ac,
791 periph->path, arg);
792 }
793 xpt_free_path(periph->path);
794 free(periph, M_CAMPERIPH);
795 xpt_lock_buses();
796 }
797
798 /*
799 * Map user virtual pointers into kernel virtual address space, so we can
800 * access the memory. This is now a generic function that centralizes most
801 * of the sanity checks on the data flags, if any.
802 * This also only works for up to maxphys memory. Since we use
803 * buffers to map stuff in and out, we're limited to the buffer size.
804 */
805 int
cam_periph_mapmem(union ccb * ccb,struct cam_periph_map_info * mapinfo,u_int maxmap)806 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo,
807 u_int maxmap)
808 {
809 int numbufs, i;
810 uint8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
811 uint32_t lengths[CAM_PERIPH_MAXMAPS];
812 uint32_t dirs[CAM_PERIPH_MAXMAPS];
813
814 bzero(mapinfo, sizeof(*mapinfo));
815 if (maxmap == 0)
816 maxmap = DFLTPHYS; /* traditional default */
817 else if (maxmap > maxphys)
818 maxmap = maxphys; /* for safety */
819 switch(ccb->ccb_h.func_code) {
820 case XPT_DEV_MATCH:
821 if (ccb->cdm.match_buf_len == 0) {
822 printf("cam_periph_mapmem: invalid match buffer "
823 "length 0\n");
824 return(EINVAL);
825 }
826 if (ccb->cdm.pattern_buf_len > 0) {
827 data_ptrs[0] = (uint8_t **)&ccb->cdm.patterns;
828 lengths[0] = ccb->cdm.pattern_buf_len;
829 dirs[0] = CAM_DIR_OUT;
830 data_ptrs[1] = (uint8_t **)&ccb->cdm.matches;
831 lengths[1] = ccb->cdm.match_buf_len;
832 dirs[1] = CAM_DIR_IN;
833 numbufs = 2;
834 } else {
835 data_ptrs[0] = (uint8_t **)&ccb->cdm.matches;
836 lengths[0] = ccb->cdm.match_buf_len;
837 dirs[0] = CAM_DIR_IN;
838 numbufs = 1;
839 }
840 /*
841 * This request will not go to the hardware, no reason
842 * to be so strict. vmapbuf() is able to map up to maxphys.
843 */
844 maxmap = maxphys;
845 break;
846 case XPT_SCSI_IO:
847 case XPT_CONT_TARGET_IO:
848 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
849 return(0);
850 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
851 return (EINVAL);
852 data_ptrs[0] = &ccb->csio.data_ptr;
853 lengths[0] = ccb->csio.dxfer_len;
854 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
855 numbufs = 1;
856 break;
857 case XPT_ATA_IO:
858 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
859 return(0);
860 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
861 return (EINVAL);
862 data_ptrs[0] = &ccb->ataio.data_ptr;
863 lengths[0] = ccb->ataio.dxfer_len;
864 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
865 numbufs = 1;
866 break;
867 case XPT_MMC_IO:
868 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
869 return(0);
870 /* Two mappings: one for cmd->data and one for cmd->data->data */
871 data_ptrs[0] = (unsigned char **)&ccb->mmcio.cmd.data;
872 lengths[0] = sizeof(struct mmc_data *);
873 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
874 data_ptrs[1] = (unsigned char **)&ccb->mmcio.cmd.data->data;
875 lengths[1] = ccb->mmcio.cmd.data->len;
876 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
877 numbufs = 2;
878 break;
879 case XPT_SMP_IO:
880 data_ptrs[0] = &ccb->smpio.smp_request;
881 lengths[0] = ccb->smpio.smp_request_len;
882 dirs[0] = CAM_DIR_OUT;
883 data_ptrs[1] = &ccb->smpio.smp_response;
884 lengths[1] = ccb->smpio.smp_response_len;
885 dirs[1] = CAM_DIR_IN;
886 numbufs = 2;
887 break;
888 case XPT_NVME_IO:
889 case XPT_NVME_ADMIN:
890 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
891 return (0);
892 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
893 return (EINVAL);
894 data_ptrs[0] = &ccb->nvmeio.data_ptr;
895 lengths[0] = ccb->nvmeio.dxfer_len;
896 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
897 numbufs = 1;
898 break;
899 case XPT_DEV_ADVINFO:
900 if (ccb->cdai.bufsiz == 0)
901 return (0);
902
903 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
904 lengths[0] = ccb->cdai.bufsiz;
905 dirs[0] = CAM_DIR_IN;
906 numbufs = 1;
907
908 /*
909 * This request will not go to the hardware, no reason
910 * to be so strict. vmapbuf() is able to map up to maxphys.
911 */
912 maxmap = maxphys;
913 break;
914 default:
915 return(EINVAL);
916 break; /* NOTREACHED */
917 }
918
919 /*
920 * Check the transfer length and permissions first, so we don't
921 * have to unmap any previously mapped buffers.
922 */
923 for (i = 0; i < numbufs; i++) {
924 if (lengths[i] > maxmap) {
925 printf("cam_periph_mapmem: attempt to map %lu bytes, "
926 "which is greater than %lu\n",
927 (long)(lengths[i]), (u_long)maxmap);
928 return (E2BIG);
929 }
930 }
931
932 /*
933 * This keeps the kernel stack of current thread from getting
934 * swapped. In low-memory situations where the kernel stack might
935 * otherwise get swapped out, this holds it and allows the thread
936 * to make progress and release the kernel mapped pages sooner.
937 *
938 * XXX KDM should I use P_NOSWAP instead?
939 */
940 PHOLD(curproc);
941
942 for (i = 0; i < numbufs; i++) {
943 /* Save the user's data address. */
944 mapinfo->orig[i] = *data_ptrs[i];
945
946 /*
947 * For small buffers use malloc+copyin/copyout instead of
948 * mapping to KVA to avoid expensive TLB shootdowns. For
949 * small allocations malloc is backed by UMA, and so much
950 * cheaper on SMP systems.
951 */
952 if (lengths[i] <= periph_mapmem_thresh &&
953 ccb->ccb_h.func_code != XPT_MMC_IO) {
954 *data_ptrs[i] = malloc(lengths[i], M_CAMPERIPH,
955 M_WAITOK);
956 if (dirs[i] != CAM_DIR_IN) {
957 if (copyin(mapinfo->orig[i], *data_ptrs[i],
958 lengths[i]) != 0) {
959 free(*data_ptrs[i], M_CAMPERIPH);
960 *data_ptrs[i] = mapinfo->orig[i];
961 goto fail;
962 }
963 } else
964 bzero(*data_ptrs[i], lengths[i]);
965 continue;
966 }
967
968 /*
969 * Get the buffer.
970 */
971 mapinfo->bp[i] = uma_zalloc(pbuf_zone, M_WAITOK);
972
973 /* set the direction */
974 mapinfo->bp[i]->b_iocmd = (dirs[i] == CAM_DIR_OUT) ?
975 BIO_WRITE : BIO_READ;
976
977 /* Map the buffer into kernel memory. */
978 if (vmapbuf(mapinfo->bp[i], *data_ptrs[i], lengths[i], 1) < 0) {
979 uma_zfree(pbuf_zone, mapinfo->bp[i]);
980 goto fail;
981 }
982
983 /* set our pointer to the new mapped area */
984 *data_ptrs[i] = mapinfo->bp[i]->b_data;
985 }
986
987 /*
988 * Now that we've gotten this far, change ownership to the kernel
989 * of the buffers so that we don't run afoul of returning to user
990 * space with locks (on the buffer) held.
991 */
992 for (i = 0; i < numbufs; i++) {
993 if (mapinfo->bp[i])
994 BUF_KERNPROC(mapinfo->bp[i]);
995 }
996
997 mapinfo->num_bufs_used = numbufs;
998 return(0);
999
1000 fail:
1001 for (i--; i >= 0; i--) {
1002 if (mapinfo->bp[i]) {
1003 vunmapbuf(mapinfo->bp[i]);
1004 uma_zfree(pbuf_zone, mapinfo->bp[i]);
1005 } else
1006 free(*data_ptrs[i], M_CAMPERIPH);
1007 *data_ptrs[i] = mapinfo->orig[i];
1008 }
1009 PRELE(curproc);
1010 return(EACCES);
1011 }
1012
1013 /*
1014 * Unmap memory segments mapped into kernel virtual address space by
1015 * cam_periph_mapmem().
1016 */
1017 int
cam_periph_unmapmem(union ccb * ccb,struct cam_periph_map_info * mapinfo)1018 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
1019 {
1020 int error, numbufs, i;
1021 uint8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1022 uint32_t lengths[CAM_PERIPH_MAXMAPS];
1023 uint32_t dirs[CAM_PERIPH_MAXMAPS];
1024
1025 if (mapinfo->num_bufs_used <= 0) {
1026 /* nothing to free and the process wasn't held. */
1027 return (0);
1028 }
1029
1030 switch (ccb->ccb_h.func_code) {
1031 case XPT_DEV_MATCH:
1032 if (ccb->cdm.pattern_buf_len > 0) {
1033 data_ptrs[0] = (uint8_t **)&ccb->cdm.patterns;
1034 lengths[0] = ccb->cdm.pattern_buf_len;
1035 dirs[0] = CAM_DIR_OUT;
1036 data_ptrs[1] = (uint8_t **)&ccb->cdm.matches;
1037 lengths[1] = ccb->cdm.match_buf_len;
1038 dirs[1] = CAM_DIR_IN;
1039 numbufs = 2;
1040 } else {
1041 data_ptrs[0] = (uint8_t **)&ccb->cdm.matches;
1042 lengths[0] = ccb->cdm.match_buf_len;
1043 dirs[0] = CAM_DIR_IN;
1044 numbufs = 1;
1045 }
1046 break;
1047 case XPT_SCSI_IO:
1048 case XPT_CONT_TARGET_IO:
1049 data_ptrs[0] = &ccb->csio.data_ptr;
1050 lengths[0] = ccb->csio.dxfer_len;
1051 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1052 numbufs = 1;
1053 break;
1054 case XPT_ATA_IO:
1055 data_ptrs[0] = &ccb->ataio.data_ptr;
1056 lengths[0] = ccb->ataio.dxfer_len;
1057 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1058 numbufs = 1;
1059 break;
1060 case XPT_MMC_IO:
1061 data_ptrs[0] = (uint8_t **)&ccb->mmcio.cmd.data;
1062 lengths[0] = sizeof(struct mmc_data *);
1063 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1064 data_ptrs[1] = (uint8_t **)&ccb->mmcio.cmd.data->data;
1065 lengths[1] = ccb->mmcio.cmd.data->len;
1066 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
1067 numbufs = 2;
1068 break;
1069 case XPT_SMP_IO:
1070 data_ptrs[0] = &ccb->smpio.smp_request;
1071 lengths[0] = ccb->smpio.smp_request_len;
1072 dirs[0] = CAM_DIR_OUT;
1073 data_ptrs[1] = &ccb->smpio.smp_response;
1074 lengths[1] = ccb->smpio.smp_response_len;
1075 dirs[1] = CAM_DIR_IN;
1076 numbufs = 2;
1077 break;
1078 case XPT_NVME_IO:
1079 case XPT_NVME_ADMIN:
1080 data_ptrs[0] = &ccb->nvmeio.data_ptr;
1081 lengths[0] = ccb->nvmeio.dxfer_len;
1082 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1083 numbufs = 1;
1084 break;
1085 case XPT_DEV_ADVINFO:
1086 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1087 lengths[0] = ccb->cdai.bufsiz;
1088 dirs[0] = CAM_DIR_IN;
1089 numbufs = 1;
1090 break;
1091 default:
1092 numbufs = 0;
1093 break;
1094 }
1095
1096 error = 0;
1097 for (i = 0; i < numbufs; i++) {
1098 if (mapinfo->bp[i]) {
1099 /* unmap the buffer */
1100 vunmapbuf(mapinfo->bp[i]);
1101
1102 /* release the buffer */
1103 uma_zfree(pbuf_zone, mapinfo->bp[i]);
1104 } else {
1105 if (dirs[i] != CAM_DIR_OUT) {
1106 int error1;
1107
1108 error1 = copyout(*data_ptrs[i], mapinfo->orig[i],
1109 lengths[i]);
1110 if (error == 0)
1111 error = error1;
1112 }
1113 free(*data_ptrs[i], M_CAMPERIPH);
1114 }
1115
1116 /* Set the user's pointer back to the original value */
1117 *data_ptrs[i] = mapinfo->orig[i];
1118 }
1119
1120 /* allow ourselves to be swapped once again */
1121 PRELE(curproc);
1122
1123 return (error);
1124 }
1125
1126 int
cam_periph_ioctl(struct cam_periph * periph,u_long cmd,caddr_t addr,int (* error_routine)(union ccb * ccb,cam_flags camflags,uint32_t sense_flags))1127 cam_periph_ioctl(struct cam_periph *periph, u_long cmd, caddr_t addr,
1128 int (*error_routine)(union ccb *ccb,
1129 cam_flags camflags,
1130 uint32_t sense_flags))
1131 {
1132 union ccb *ccb;
1133 int error;
1134 int found;
1135
1136 error = found = 0;
1137
1138 switch(cmd){
1139 case CAMGETPASSTHRU_0x19:
1140 case CAMGETPASSTHRU:
1141 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1142 xpt_setup_ccb(&ccb->ccb_h,
1143 ccb->ccb_h.path,
1144 CAM_PRIORITY_NORMAL);
1145 ccb->ccb_h.func_code = XPT_GDEVLIST;
1146
1147 /*
1148 * Basically, the point of this is that we go through
1149 * getting the list of devices, until we find a passthrough
1150 * device. In the current version of the CAM code, the
1151 * only way to determine what type of device we're dealing
1152 * with is by its name.
1153 */
1154 while (found == 0) {
1155 ccb->cgdl.index = 0;
1156 ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
1157 while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
1158 /* we want the next device in the list */
1159 xpt_action(ccb);
1160 if (strncmp(ccb->cgdl.periph_name,
1161 "pass", 4) == 0){
1162 found = 1;
1163 break;
1164 }
1165 }
1166 if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
1167 (found == 0)) {
1168 ccb->cgdl.periph_name[0] = '\0';
1169 ccb->cgdl.unit_number = 0;
1170 break;
1171 }
1172 }
1173
1174 /* copy the result back out */
1175 bcopy(ccb, addr, sizeof(union ccb));
1176
1177 /* and release the ccb */
1178 xpt_release_ccb(ccb);
1179
1180 break;
1181 default:
1182 error = ENOTTY;
1183 break;
1184 }
1185 return(error);
1186 }
1187
1188 static void
cam_periph_done_panic(struct cam_periph * periph,union ccb * done_ccb)1189 cam_periph_done_panic(struct cam_periph *periph, union ccb *done_ccb)
1190 {
1191
1192 panic("%s: already done with ccb %p", __func__, done_ccb);
1193 }
1194
1195 static void
cam_periph_done(struct cam_periph * periph,union ccb * done_ccb)1196 cam_periph_done(struct cam_periph *periph, union ccb *done_ccb)
1197 {
1198
1199 /* Caller will release the CCB */
1200 xpt_path_assert(done_ccb->ccb_h.path, MA_OWNED);
1201 done_ccb->ccb_h.cbfcnp = cam_periph_done_panic;
1202 wakeup(&done_ccb->ccb_h.cbfcnp);
1203 }
1204
1205 static void
cam_periph_ccbwait(union ccb * ccb)1206 cam_periph_ccbwait(union ccb *ccb)
1207 {
1208
1209 if ((ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
1210 while (ccb->ccb_h.cbfcnp != cam_periph_done_panic)
1211 xpt_path_sleep(ccb->ccb_h.path, &ccb->ccb_h.cbfcnp,
1212 PRIBIO, "cbwait", 0);
1213 }
1214 KASSERT(ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX &&
1215 (ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG,
1216 ("%s: proceeding with incomplete ccb: ccb=%p, func_code=%#x, "
1217 "status=%#x, index=%d", __func__, ccb, ccb->ccb_h.func_code,
1218 ccb->ccb_h.status, ccb->ccb_h.pinfo.index));
1219 }
1220
1221 /*
1222 * Dispatch a CCB and wait for it to complete. If the CCB has set a
1223 * callback function (ccb->ccb_h.cbfcnp), it will be overwritten and lost.
1224 */
1225 int
cam_periph_runccb(union ccb * ccb,int (* error_routine)(union ccb * ccb,cam_flags camflags,uint32_t sense_flags),cam_flags camflags,uint32_t sense_flags,struct devstat * ds)1226 cam_periph_runccb(union ccb *ccb,
1227 int (*error_routine)(union ccb *ccb,
1228 cam_flags camflags,
1229 uint32_t sense_flags),
1230 cam_flags camflags, uint32_t sense_flags,
1231 struct devstat *ds)
1232 {
1233 struct bintime *starttime;
1234 struct bintime ltime;
1235 int error;
1236 bool must_poll;
1237 uint32_t timeout = 1;
1238
1239 starttime = NULL;
1240 xpt_path_assert(ccb->ccb_h.path, MA_OWNED);
1241 KASSERT((ccb->ccb_h.flags & CAM_UNLOCKED) == 0,
1242 ("%s: ccb=%p, func_code=%#x, flags=%#x", __func__, ccb,
1243 ccb->ccb_h.func_code, ccb->ccb_h.flags));
1244
1245 /*
1246 * If the user has supplied a stats structure, and if we understand
1247 * this particular type of ccb, record the transaction start.
1248 */
1249 if (ds != NULL &&
1250 (ccb->ccb_h.func_code == XPT_SCSI_IO ||
1251 ccb->ccb_h.func_code == XPT_ATA_IO ||
1252 ccb->ccb_h.func_code == XPT_NVME_IO)) {
1253 starttime = <ime;
1254 binuptime(starttime);
1255 devstat_start_transaction(ds, starttime);
1256 }
1257
1258 /*
1259 * We must poll the I/O while we're dumping. The scheduler is normally
1260 * stopped for dumping, except when we call doadump from ddb. While the
1261 * scheduler is running in this case, we still need to poll the I/O to
1262 * avoid sleeping waiting for the ccb to complete.
1263 *
1264 * A panic triggered dump stops the scheduler, any callback from the
1265 * shutdown_post_sync event will run with the scheduler stopped, but
1266 * before we're officially dumping. To avoid hanging in adashutdown
1267 * initiated commands (or other similar situations), we have to test for
1268 * either dumping or SCHEDULER_STOPPED() here.
1269 *
1270 * To avoid locking problems, dumping/polling callers must call
1271 * without a periph lock held.
1272 */
1273 must_poll = dumping || SCHEDULER_STOPPED();
1274 ccb->ccb_h.cbfcnp = cam_periph_done;
1275
1276 /*
1277 * If we're polling, then we need to ensure that we have ample resources
1278 * in the periph. cam_periph_error can reschedule the ccb by calling
1279 * xpt_action and returning ERESTART, so we have to effect the polling
1280 * in the do loop below.
1281 */
1282 if (must_poll) {
1283 if (cam_sim_pollable(ccb->ccb_h.path->bus->sim))
1284 timeout = xpt_poll_setup(ccb);
1285 else
1286 timeout = 0;
1287 }
1288
1289 if (timeout == 0) {
1290 ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
1291 error = EBUSY;
1292 } else {
1293 xpt_action(ccb);
1294 do {
1295 if (must_poll) {
1296 xpt_pollwait(ccb, timeout);
1297 timeout = ccb->ccb_h.timeout * 10;
1298 } else {
1299 cam_periph_ccbwait(ccb);
1300 }
1301 if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1302 error = 0;
1303 else if (error_routine != NULL) {
1304 /*
1305 * cbfcnp is modified by cam_periph_ccbwait so
1306 * reset it before we call the error routine
1307 * which may call xpt_done.
1308 */
1309 ccb->ccb_h.cbfcnp = cam_periph_done;
1310 error = (*error_routine)(ccb, camflags, sense_flags);
1311 } else
1312 error = 0;
1313 } while (error == ERESTART);
1314 }
1315
1316 if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1317 cam_release_devq(ccb->ccb_h.path,
1318 /* relsim_flags */0,
1319 /* openings */0,
1320 /* timeout */0,
1321 /* getcount_only */ FALSE);
1322 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1323 }
1324
1325 if (ds != NULL) {
1326 uint32_t bytes;
1327 devstat_tag_type tag;
1328 bool valid = true;
1329
1330 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1331 bytes = ccb->csio.dxfer_len - ccb->csio.resid;
1332 tag = (devstat_tag_type)(ccb->csio.tag_action & 0x3);
1333 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1334 bytes = ccb->ataio.dxfer_len - ccb->ataio.resid;
1335 tag = (devstat_tag_type)0;
1336 } else if (ccb->ccb_h.func_code == XPT_NVME_IO) {
1337 bytes = ccb->nvmeio.dxfer_len; /* NB: resid no possible */
1338 tag = (devstat_tag_type)0;
1339 } else {
1340 valid = false;
1341 }
1342 if (valid)
1343 devstat_end_transaction(ds, bytes, tag,
1344 ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE) ?
1345 DEVSTAT_NO_DATA : (ccb->ccb_h.flags & CAM_DIR_OUT) ?
1346 DEVSTAT_WRITE : DEVSTAT_READ, NULL, starttime);
1347 }
1348
1349 return(error);
1350 }
1351
1352 void
cam_freeze_devq(struct cam_path * path)1353 cam_freeze_devq(struct cam_path *path)
1354 {
1355 struct ccb_hdr ccb_h;
1356
1357 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_freeze_devq\n"));
1358 memset(&ccb_h, 0, sizeof(ccb_h));
1359 xpt_setup_ccb(&ccb_h, path, /*priority*/1);
1360 ccb_h.func_code = XPT_NOOP;
1361 ccb_h.flags = CAM_DEV_QFREEZE;
1362 xpt_action((union ccb *)&ccb_h);
1363 }
1364
1365 uint32_t
cam_release_devq(struct cam_path * path,uint32_t relsim_flags,uint32_t openings,uint32_t arg,int getcount_only)1366 cam_release_devq(struct cam_path *path, uint32_t relsim_flags,
1367 uint32_t openings, uint32_t arg,
1368 int getcount_only)
1369 {
1370 struct ccb_relsim crs;
1371
1372 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_release_devq(%u, %u, %u, %d)\n",
1373 relsim_flags, openings, arg, getcount_only));
1374 memset(&crs, 0, sizeof(crs));
1375 xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
1376 crs.ccb_h.func_code = XPT_REL_SIMQ;
1377 crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
1378 crs.release_flags = relsim_flags;
1379 crs.openings = openings;
1380 crs.release_timeout = arg;
1381 xpt_action((union ccb *)&crs);
1382 return (crs.qfrozen_cnt);
1383 }
1384
1385 #define saved_ccb_ptr ppriv_ptr0
1386 static void
camperiphdone(struct cam_periph * periph,union ccb * done_ccb)1387 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
1388 {
1389 union ccb *saved_ccb;
1390 cam_status status;
1391 struct scsi_start_stop_unit *scsi_cmd;
1392 int error = 0, error_code, sense_key, asc, ascq;
1393 uint16_t done_flags;
1394
1395 scsi_cmd = (struct scsi_start_stop_unit *)
1396 &done_ccb->csio.cdb_io.cdb_bytes;
1397 status = done_ccb->ccb_h.status;
1398
1399 if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1400 if (scsi_extract_sense_ccb(done_ccb,
1401 &error_code, &sense_key, &asc, &ascq)) {
1402 /*
1403 * If the error is "invalid field in CDB",
1404 * and the load/eject flag is set, turn the
1405 * flag off and try again. This is just in
1406 * case the drive in question barfs on the
1407 * load eject flag. The CAM code should set
1408 * the load/eject flag by default for
1409 * removable media.
1410 */
1411 if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1412 ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1413 (asc == 0x24) && (ascq == 0x00)) {
1414 scsi_cmd->how &= ~SSS_LOEJ;
1415 if (status & CAM_DEV_QFRZN) {
1416 cam_release_devq(done_ccb->ccb_h.path,
1417 0, 0, 0, 0);
1418 done_ccb->ccb_h.status &=
1419 ~CAM_DEV_QFRZN;
1420 }
1421 xpt_action(done_ccb);
1422 goto out;
1423 }
1424 }
1425 error = cam_periph_error(done_ccb, 0,
1426 SF_RETRY_UA | SF_NO_PRINT);
1427 if (error == ERESTART)
1428 goto out;
1429 if (done_ccb->ccb_h.status & CAM_DEV_QFRZN) {
1430 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1431 done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1432 }
1433 } else {
1434 /*
1435 * If we have successfully taken a device from the not
1436 * ready to ready state, re-scan the device and re-get
1437 * the inquiry information. Many devices (mostly disks)
1438 * don't properly report their inquiry information unless
1439 * they are spun up.
1440 */
1441 if (scsi_cmd->opcode == START_STOP_UNIT)
1442 xpt_async(AC_INQ_CHANGED, done_ccb->ccb_h.path, NULL);
1443 }
1444
1445 /* If we tried long wait and still failed, remember that. */
1446 if ((periph->flags & CAM_PERIPH_RECOVERY_WAIT) &&
1447 (done_ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY)) {
1448 periph->flags &= ~CAM_PERIPH_RECOVERY_WAIT;
1449 if (error != 0 && done_ccb->ccb_h.retry_count == 0)
1450 periph->flags |= CAM_PERIPH_RECOVERY_WAIT_FAILED;
1451 }
1452
1453 /*
1454 * After recovery action(s) completed, return to the original CCB.
1455 * If the recovery CCB has failed, considering its own possible
1456 * retries and recovery, assume we are back in state where we have
1457 * been originally, but without recovery hopes left. In such case,
1458 * after the final attempt below, we cancel any further retries,
1459 * blocking by that also any new recovery attempts for this CCB,
1460 * and the result will be the final one returned to the CCB owher.
1461 */
1462 saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1463 KASSERT(saved_ccb->ccb_h.func_code == XPT_SCSI_IO,
1464 ("%s: saved_ccb func_code %#x != XPT_SCSI_IO",
1465 __func__, saved_ccb->ccb_h.func_code));
1466 KASSERT(done_ccb->ccb_h.func_code == XPT_SCSI_IO,
1467 ("%s: done_ccb func_code %#x != XPT_SCSI_IO",
1468 __func__, done_ccb->ccb_h.func_code));
1469 saved_ccb->ccb_h.periph_links = done_ccb->ccb_h.periph_links;
1470 done_flags = done_ccb->ccb_h.alloc_flags;
1471 bcopy(saved_ccb, done_ccb, sizeof(struct ccb_scsiio));
1472 done_ccb->ccb_h.alloc_flags = done_flags;
1473 xpt_free_ccb(saved_ccb);
1474 if (done_ccb->ccb_h.cbfcnp != camperiphdone)
1475 periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1476 if (error != 0)
1477 done_ccb->ccb_h.retry_count = 0;
1478 xpt_action(done_ccb);
1479
1480 out:
1481 /* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1482 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1483 }
1484
1485 /*
1486 * Generic Async Event handler. Peripheral drivers usually
1487 * filter out the events that require personal attention,
1488 * and leave the rest to this function.
1489 */
1490 void
cam_periph_async(struct cam_periph * periph,uint32_t code,struct cam_path * path,void * arg)1491 cam_periph_async(struct cam_periph *periph, uint32_t code,
1492 struct cam_path *path, void *arg)
1493 {
1494 switch (code) {
1495 case AC_LOST_DEVICE:
1496 cam_periph_invalidate(periph);
1497 break;
1498 default:
1499 break;
1500 }
1501 }
1502
1503 void
cam_periph_bus_settle(struct cam_periph * periph,u_int bus_settle)1504 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1505 {
1506 struct ccb_getdevstats cgds;
1507
1508 memset(&cgds, 0, sizeof(cgds));
1509 xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1510 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1511 xpt_action((union ccb *)&cgds);
1512 cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1513 }
1514
1515 void
cam_periph_freeze_after_event(struct cam_periph * periph,struct timeval * event_time,u_int duration_ms)1516 cam_periph_freeze_after_event(struct cam_periph *periph,
1517 struct timeval* event_time, u_int duration_ms)
1518 {
1519 struct timeval delta;
1520 struct timeval duration_tv;
1521
1522 if (!timevalisset(event_time))
1523 return;
1524
1525 microtime(&delta);
1526 timevalsub(&delta, event_time);
1527 duration_tv.tv_sec = duration_ms / 1000;
1528 duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1529 if (timevalcmp(&delta, &duration_tv, <)) {
1530 timevalsub(&duration_tv, &delta);
1531
1532 duration_ms = duration_tv.tv_sec * 1000;
1533 duration_ms += duration_tv.tv_usec / 1000;
1534 cam_freeze_devq(periph->path);
1535 cam_release_devq(periph->path,
1536 RELSIM_RELEASE_AFTER_TIMEOUT,
1537 /*reduction*/0,
1538 /*timeout*/duration_ms,
1539 /*getcount_only*/0);
1540 }
1541
1542 }
1543
1544 static int
camperiphscsistatuserror(union ccb * ccb,union ccb ** orig_ccb,cam_flags camflags,uint32_t sense_flags,int * openings,uint32_t * relsim_flags,uint32_t * timeout,uint32_t * action,const char ** action_string)1545 camperiphscsistatuserror(union ccb *ccb, union ccb **orig_ccb,
1546 cam_flags camflags, uint32_t sense_flags,
1547 int *openings, uint32_t *relsim_flags,
1548 uint32_t *timeout, uint32_t *action, const char **action_string)
1549 {
1550 struct cam_periph *periph;
1551 int error;
1552
1553 switch (ccb->csio.scsi_status) {
1554 case SCSI_STATUS_OK:
1555 case SCSI_STATUS_COND_MET:
1556 case SCSI_STATUS_INTERMED:
1557 case SCSI_STATUS_INTERMED_COND_MET:
1558 error = 0;
1559 break;
1560 case SCSI_STATUS_CMD_TERMINATED:
1561 case SCSI_STATUS_CHECK_COND:
1562 error = camperiphscsisenseerror(ccb, orig_ccb,
1563 camflags,
1564 sense_flags,
1565 openings,
1566 relsim_flags,
1567 timeout,
1568 action,
1569 action_string);
1570 break;
1571 case SCSI_STATUS_QUEUE_FULL:
1572 {
1573 /* no decrement */
1574 struct ccb_getdevstats cgds;
1575
1576 /*
1577 * First off, find out what the current
1578 * transaction counts are.
1579 */
1580 memset(&cgds, 0, sizeof(cgds));
1581 xpt_setup_ccb(&cgds.ccb_h,
1582 ccb->ccb_h.path,
1583 CAM_PRIORITY_NORMAL);
1584 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1585 xpt_action((union ccb *)&cgds);
1586
1587 /*
1588 * If we were the only transaction active, treat
1589 * the QUEUE FULL as if it were a BUSY condition.
1590 */
1591 if (cgds.dev_active != 0) {
1592 int total_openings;
1593
1594 /*
1595 * Reduce the number of openings to
1596 * be 1 less than the amount it took
1597 * to get a queue full bounded by the
1598 * minimum allowed tag count for this
1599 * device.
1600 */
1601 total_openings = cgds.dev_active + cgds.dev_openings;
1602 *openings = cgds.dev_active;
1603 if (*openings < cgds.mintags)
1604 *openings = cgds.mintags;
1605 if (*openings < total_openings)
1606 *relsim_flags = RELSIM_ADJUST_OPENINGS;
1607 else {
1608 /*
1609 * Some devices report queue full for
1610 * temporary resource shortages. For
1611 * this reason, we allow a minimum
1612 * tag count to be entered via a
1613 * quirk entry to prevent the queue
1614 * count on these devices from falling
1615 * to a pessimisticly low value. We
1616 * still wait for the next successful
1617 * completion, however, before queueing
1618 * more transactions to the device.
1619 */
1620 *relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1621 }
1622 *timeout = 0;
1623 error = ERESTART;
1624 *action &= ~SSQ_PRINT_SENSE;
1625 break;
1626 }
1627 /* FALLTHROUGH */
1628 }
1629 case SCSI_STATUS_BUSY:
1630 /*
1631 * Restart the queue after either another
1632 * command completes or a 1 second timeout.
1633 */
1634 periph = xpt_path_periph(ccb->ccb_h.path);
1635 if (periph->flags & CAM_PERIPH_INVALID) {
1636 error = ENXIO;
1637 *action_string = "Periph was invalidated";
1638 } else if ((sense_flags & SF_RETRY_BUSY) != 0 ||
1639 ccb->ccb_h.retry_count > 0) {
1640 if ((sense_flags & SF_RETRY_BUSY) == 0)
1641 ccb->ccb_h.retry_count--;
1642 error = ERESTART;
1643 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1644 | RELSIM_RELEASE_AFTER_CMDCMPLT;
1645 *timeout = 1000;
1646 } else {
1647 error = EIO;
1648 *action_string = "Retries exhausted";
1649 }
1650 break;
1651 case SCSI_STATUS_RESERV_CONFLICT:
1652 default:
1653 error = EIO;
1654 break;
1655 }
1656 return (error);
1657 }
1658
1659 static int
camperiphscsisenseerror(union ccb * ccb,union ccb ** orig,cam_flags camflags,uint32_t sense_flags,int * openings,uint32_t * relsim_flags,uint32_t * timeout,uint32_t * action,const char ** action_string)1660 camperiphscsisenseerror(union ccb *ccb, union ccb **orig,
1661 cam_flags camflags, uint32_t sense_flags,
1662 int *openings, uint32_t *relsim_flags,
1663 uint32_t *timeout, uint32_t *action, const char **action_string)
1664 {
1665 struct cam_periph *periph;
1666 union ccb *orig_ccb = ccb;
1667 int error, recoveryccb;
1668 uint16_t flags;
1669
1670 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1671 if (ccb->ccb_h.func_code == XPT_SCSI_IO && ccb->csio.bio != NULL)
1672 biotrack(ccb->csio.bio, __func__);
1673 #endif
1674
1675 periph = xpt_path_periph(ccb->ccb_h.path);
1676 recoveryccb = (ccb->ccb_h.cbfcnp == camperiphdone);
1677 if ((periph->flags & CAM_PERIPH_RECOVERY_INPROG) && !recoveryccb) {
1678 /*
1679 * If error recovery is already in progress, don't attempt
1680 * to process this error, but requeue it unconditionally
1681 * and attempt to process it once error recovery has
1682 * completed. This failed command is probably related to
1683 * the error that caused the currently active error recovery
1684 * action so our current recovery efforts should also
1685 * address this command. Be aware that the error recovery
1686 * code assumes that only one recovery action is in progress
1687 * on a particular peripheral instance at any given time
1688 * (e.g. only one saved CCB for error recovery) so it is
1689 * imperitive that we don't violate this assumption.
1690 */
1691 error = ERESTART;
1692 *action &= ~SSQ_PRINT_SENSE;
1693 } else {
1694 scsi_sense_action err_action;
1695 struct ccb_getdev cgd;
1696
1697 /*
1698 * Grab the inquiry data for this device.
1699 */
1700 memset(&cgd, 0, sizeof(cgd));
1701 xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, CAM_PRIORITY_NORMAL);
1702 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1703 xpt_action((union ccb *)&cgd);
1704
1705 err_action = scsi_error_action(&ccb->csio, &cgd.inq_data,
1706 sense_flags);
1707 error = err_action & SS_ERRMASK;
1708
1709 /*
1710 * Do not autostart sequential access devices
1711 * to avoid unexpected tape loading.
1712 */
1713 if ((err_action & SS_MASK) == SS_START &&
1714 SID_TYPE(&cgd.inq_data) == T_SEQUENTIAL) {
1715 *action_string = "Will not autostart a "
1716 "sequential access device";
1717 goto sense_error_done;
1718 }
1719
1720 /*
1721 * Avoid recovery recursion if recovery action is the same.
1722 */
1723 if ((err_action & SS_MASK) >= SS_START && recoveryccb) {
1724 if (((err_action & SS_MASK) == SS_START &&
1725 ccb->csio.cdb_io.cdb_bytes[0] == START_STOP_UNIT) ||
1726 ((err_action & SS_MASK) == SS_TUR &&
1727 (ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY))) {
1728 err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1729 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1730 *timeout = 500;
1731 }
1732 }
1733
1734 /*
1735 * If the recovery action will consume a retry,
1736 * make sure we actually have retries available.
1737 */
1738 if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1739 if (ccb->ccb_h.retry_count > 0 &&
1740 (periph->flags & CAM_PERIPH_INVALID) == 0)
1741 ccb->ccb_h.retry_count--;
1742 else {
1743 *action_string = "Retries exhausted";
1744 goto sense_error_done;
1745 }
1746 }
1747
1748 if ((err_action & SS_MASK) >= SS_START) {
1749 /*
1750 * Do common portions of commands that
1751 * use recovery CCBs.
1752 */
1753 orig_ccb = xpt_alloc_ccb_nowait();
1754 if (orig_ccb == NULL) {
1755 *action_string = "Can't allocate recovery CCB";
1756 goto sense_error_done;
1757 }
1758 /*
1759 * Clear freeze flag for original request here, as
1760 * this freeze will be dropped as part of ERESTART.
1761 */
1762 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1763
1764 KASSERT(ccb->ccb_h.func_code == XPT_SCSI_IO,
1765 ("%s: ccb func_code %#x != XPT_SCSI_IO",
1766 __func__, ccb->ccb_h.func_code));
1767 flags = orig_ccb->ccb_h.alloc_flags;
1768 bcopy(ccb, orig_ccb, sizeof(struct ccb_scsiio));
1769 orig_ccb->ccb_h.alloc_flags = flags;
1770 }
1771
1772 switch (err_action & SS_MASK) {
1773 case SS_NOP:
1774 *action_string = "No recovery action needed";
1775 error = 0;
1776 break;
1777 case SS_RETRY:
1778 *action_string = "Retrying command (per sense data)";
1779 error = ERESTART;
1780 break;
1781 case SS_FAIL:
1782 *action_string = "Unretryable error";
1783 break;
1784 case SS_START:
1785 {
1786 int le;
1787
1788 /*
1789 * Send a start unit command to the device, and
1790 * then retry the command.
1791 */
1792 *action_string = "Attempting to start unit";
1793 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1794
1795 /*
1796 * Check for removable media and set
1797 * load/eject flag appropriately.
1798 */
1799 if (SID_IS_REMOVABLE(&cgd.inq_data))
1800 le = TRUE;
1801 else
1802 le = FALSE;
1803
1804 scsi_start_stop(&ccb->csio,
1805 /*retries*/1,
1806 camperiphdone,
1807 MSG_SIMPLE_Q_TAG,
1808 /*start*/TRUE,
1809 /*load/eject*/le,
1810 /*immediate*/FALSE,
1811 SSD_FULL_SIZE,
1812 /*timeout*/50000);
1813 break;
1814 }
1815 case SS_TUR:
1816 {
1817 /*
1818 * Send a Test Unit Ready to the device.
1819 * If the 'many' flag is set, we send 120
1820 * test unit ready commands, one every half
1821 * second. Otherwise, we just send one TUR.
1822 * We only want to do this if the retry
1823 * count has not been exhausted.
1824 */
1825 int retries;
1826
1827 if ((err_action & SSQ_MANY) != 0 && (periph->flags &
1828 CAM_PERIPH_RECOVERY_WAIT_FAILED) == 0) {
1829 periph->flags |= CAM_PERIPH_RECOVERY_WAIT;
1830 *action_string = "Polling device for readiness";
1831 retries = 120;
1832 } else {
1833 *action_string = "Testing device for readiness";
1834 retries = 1;
1835 }
1836 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1837 scsi_test_unit_ready(&ccb->csio,
1838 retries,
1839 camperiphdone,
1840 MSG_SIMPLE_Q_TAG,
1841 SSD_FULL_SIZE,
1842 /*timeout*/5000);
1843
1844 /*
1845 * Accomplish our 500ms delay by deferring
1846 * the release of our device queue appropriately.
1847 */
1848 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1849 *timeout = 500;
1850 break;
1851 }
1852 default:
1853 panic("Unhandled error action %x", err_action);
1854 }
1855
1856 if ((err_action & SS_MASK) >= SS_START) {
1857 /*
1858 * Drop the priority, so that the recovery
1859 * CCB is the first to execute. Freeze the queue
1860 * after this command is sent so that we can
1861 * restore the old csio and have it queued in
1862 * the proper order before we release normal
1863 * transactions to the device.
1864 */
1865 ccb->ccb_h.pinfo.priority--;
1866 ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1867 ccb->ccb_h.saved_ccb_ptr = orig_ccb;
1868 error = ERESTART;
1869 *orig = orig_ccb;
1870 }
1871
1872 sense_error_done:
1873 *action = err_action;
1874 }
1875 return (error);
1876 }
1877
1878 /*
1879 * Generic error handler. Peripheral drivers usually filter
1880 * out the errors that they handle in a unique manner, then
1881 * call this function.
1882 */
1883 int
cam_periph_error(union ccb * ccb,cam_flags camflags,uint32_t sense_flags)1884 cam_periph_error(union ccb *ccb, cam_flags camflags,
1885 uint32_t sense_flags)
1886 {
1887 struct cam_path *newpath;
1888 union ccb *orig_ccb, *scan_ccb;
1889 struct cam_periph *periph;
1890 const char *action_string;
1891 cam_status status;
1892 int frozen, error, openings, devctl_err;
1893 uint32_t action, relsim_flags, timeout;
1894
1895 action = SSQ_PRINT_SENSE;
1896 periph = xpt_path_periph(ccb->ccb_h.path);
1897 action_string = NULL;
1898 status = ccb->ccb_h.status;
1899 frozen = (status & CAM_DEV_QFRZN) != 0;
1900 status &= CAM_STATUS_MASK;
1901 devctl_err = openings = relsim_flags = timeout = 0;
1902 orig_ccb = ccb;
1903
1904 /* Filter the errors that should be reported via devctl */
1905 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1906 case CAM_CMD_TIMEOUT:
1907 case CAM_REQ_ABORTED:
1908 case CAM_REQ_CMP_ERR:
1909 case CAM_REQ_TERMIO:
1910 case CAM_UNREC_HBA_ERROR:
1911 case CAM_DATA_RUN_ERR:
1912 case CAM_SCSI_STATUS_ERROR:
1913 case CAM_ATA_STATUS_ERROR:
1914 case CAM_SMP_STATUS_ERROR:
1915 case CAM_DEV_NOT_THERE:
1916 case CAM_NVME_STATUS_ERROR:
1917 devctl_err++;
1918 break;
1919 default:
1920 break;
1921 }
1922
1923 switch (status) {
1924 case CAM_REQ_CMP:
1925 error = 0;
1926 action &= ~SSQ_PRINT_SENSE;
1927 break;
1928 case CAM_SCSI_STATUS_ERROR:
1929 error = camperiphscsistatuserror(ccb, &orig_ccb,
1930 camflags, sense_flags, &openings, &relsim_flags,
1931 &timeout, &action, &action_string);
1932 break;
1933 case CAM_AUTOSENSE_FAIL:
1934 error = EIO; /* we have to kill the command */
1935 break;
1936 case CAM_UA_ABORT:
1937 case CAM_UA_TERMIO:
1938 case CAM_MSG_REJECT_REC:
1939 /* XXX Don't know that these are correct */
1940 error = EIO;
1941 break;
1942 case CAM_SEL_TIMEOUT:
1943 if ((camflags & CAM_RETRY_SELTO) != 0) {
1944 if (ccb->ccb_h.retry_count > 0 &&
1945 (periph->flags & CAM_PERIPH_INVALID) == 0) {
1946 ccb->ccb_h.retry_count--;
1947 error = ERESTART;
1948
1949 /*
1950 * Wait a bit to give the device
1951 * time to recover before we try again.
1952 */
1953 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1954 timeout = periph_selto_delay;
1955 break;
1956 }
1957 action_string = "Retries exhausted";
1958 }
1959 /* FALLTHROUGH */
1960 case CAM_DEV_NOT_THERE:
1961 error = ENXIO;
1962 action = SSQ_LOST;
1963 break;
1964 case CAM_REQ_INVALID:
1965 case CAM_PATH_INVALID:
1966 case CAM_NO_HBA:
1967 case CAM_PROVIDE_FAIL:
1968 case CAM_REQ_TOO_BIG:
1969 case CAM_LUN_INVALID:
1970 case CAM_TID_INVALID:
1971 case CAM_FUNC_NOTAVAIL:
1972 error = EINVAL;
1973 break;
1974 case CAM_SCSI_BUS_RESET:
1975 case CAM_BDR_SENT:
1976 /*
1977 * Commands that repeatedly timeout and cause these
1978 * kinds of error recovery actions, should return
1979 * CAM_CMD_TIMEOUT, which allows us to safely assume
1980 * that this command was an innocent bystander to
1981 * these events and should be unconditionally
1982 * retried.
1983 */
1984 case CAM_REQUEUE_REQ:
1985 /* Unconditional requeue if device is still there */
1986 if (periph->flags & CAM_PERIPH_INVALID) {
1987 action_string = "Periph was invalidated";
1988 error = ENXIO;
1989 } else if (sense_flags & SF_NO_RETRY) {
1990 error = EIO;
1991 action_string = "Retry was blocked";
1992 } else {
1993 error = ERESTART;
1994 action &= ~SSQ_PRINT_SENSE;
1995 }
1996 break;
1997 case CAM_RESRC_UNAVAIL:
1998 /* Wait a bit for the resource shortage to abate. */
1999 timeout = periph_noresrc_delay;
2000 /* FALLTHROUGH */
2001 case CAM_BUSY:
2002 if (timeout == 0) {
2003 /* Wait a bit for the busy condition to abate. */
2004 timeout = periph_busy_delay;
2005 }
2006 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
2007 /* FALLTHROUGH */
2008 case CAM_ATA_STATUS_ERROR:
2009 case CAM_NVME_STATUS_ERROR:
2010 case CAM_SMP_STATUS_ERROR:
2011 case CAM_REQ_CMP_ERR:
2012 case CAM_CMD_TIMEOUT:
2013 case CAM_UNEXP_BUSFREE:
2014 case CAM_UNCOR_PARITY:
2015 case CAM_DATA_RUN_ERR:
2016 default:
2017 if (periph->flags & CAM_PERIPH_INVALID) {
2018 error = ENXIO;
2019 action_string = "Periph was invalidated";
2020 } else if (ccb->ccb_h.retry_count == 0) {
2021 error = EIO;
2022 action_string = "Retries exhausted";
2023 } else if (sense_flags & SF_NO_RETRY) {
2024 error = EIO;
2025 action_string = "Retry was blocked";
2026 } else {
2027 ccb->ccb_h.retry_count--;
2028 error = ERESTART;
2029 }
2030 break;
2031 }
2032
2033 if ((sense_flags & SF_PRINT_ALWAYS) ||
2034 CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO))
2035 action |= SSQ_PRINT_SENSE;
2036 else if (sense_flags & SF_NO_PRINT)
2037 action &= ~SSQ_PRINT_SENSE;
2038 if ((action & SSQ_PRINT_SENSE) != 0)
2039 cam_error_print(orig_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
2040 if (error != 0 && (action & SSQ_PRINT_SENSE) != 0) {
2041 if (error != ERESTART) {
2042 if (action_string == NULL)
2043 action_string = "Unretryable error";
2044 xpt_print(ccb->ccb_h.path, "Error %d, %s\n",
2045 error, action_string);
2046 } else if (action_string != NULL)
2047 xpt_print(ccb->ccb_h.path, "%s\n", action_string);
2048 else {
2049 xpt_print(ccb->ccb_h.path,
2050 "Retrying command, %d more tries remain\n",
2051 ccb->ccb_h.retry_count);
2052 }
2053 }
2054
2055 if (devctl_err && (error != 0 || (action & SSQ_PRINT_SENSE) != 0))
2056 cam_periph_devctl_notify(orig_ccb);
2057
2058 if ((action & SSQ_LOST) != 0) {
2059 lun_id_t lun_id;
2060
2061 /*
2062 * For a selection timeout, we consider all of the LUNs on
2063 * the target to be gone. If the status is CAM_DEV_NOT_THERE,
2064 * then we only get rid of the device(s) specified by the
2065 * path in the original CCB.
2066 */
2067 if (status == CAM_SEL_TIMEOUT)
2068 lun_id = CAM_LUN_WILDCARD;
2069 else
2070 lun_id = xpt_path_lun_id(ccb->ccb_h.path);
2071
2072 /* Should we do more if we can't create the path?? */
2073 if (xpt_create_path(&newpath, periph,
2074 xpt_path_path_id(ccb->ccb_h.path),
2075 xpt_path_target_id(ccb->ccb_h.path),
2076 lun_id) == CAM_REQ_CMP) {
2077 /*
2078 * Let peripheral drivers know that this
2079 * device has gone away.
2080 */
2081 xpt_async(AC_LOST_DEVICE, newpath, NULL);
2082 xpt_free_path(newpath);
2083 }
2084 }
2085
2086 /* Broadcast UNIT ATTENTIONs to all periphs. */
2087 if ((action & SSQ_UA) != 0)
2088 xpt_async(AC_UNIT_ATTENTION, orig_ccb->ccb_h.path, orig_ccb);
2089
2090 /* Rescan target on "Reported LUNs data has changed" */
2091 if ((action & SSQ_RESCAN) != 0) {
2092 if (xpt_create_path(&newpath, NULL,
2093 xpt_path_path_id(ccb->ccb_h.path),
2094 xpt_path_target_id(ccb->ccb_h.path),
2095 CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
2096 scan_ccb = xpt_alloc_ccb_nowait();
2097 if (scan_ccb != NULL) {
2098 scan_ccb->ccb_h.path = newpath;
2099 scan_ccb->ccb_h.func_code = XPT_SCAN_TGT;
2100 scan_ccb->crcn.flags = 0;
2101 xpt_rescan(scan_ccb);
2102 } else {
2103 xpt_print(newpath,
2104 "Can't allocate CCB to rescan target\n");
2105 xpt_free_path(newpath);
2106 }
2107 }
2108 }
2109
2110 /* Attempt a retry */
2111 if (error == ERESTART || error == 0) {
2112 if (frozen != 0)
2113 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
2114 if (error == ERESTART)
2115 xpt_action(ccb);
2116 if (frozen != 0)
2117 cam_release_devq(ccb->ccb_h.path,
2118 relsim_flags,
2119 openings,
2120 timeout,
2121 /*getcount_only*/0);
2122 }
2123
2124 return (error);
2125 }
2126
2127 #define CAM_PERIPH_DEVD_MSG_SIZE 256
2128
2129 static void
cam_periph_devctl_notify(union ccb * ccb)2130 cam_periph_devctl_notify(union ccb *ccb)
2131 {
2132 struct cam_periph *periph;
2133 struct ccb_getdev *cgd;
2134 struct sbuf sb;
2135 int serr, sk, asc, ascq;
2136 char *sbmsg, *type;
2137
2138 sbmsg = malloc(CAM_PERIPH_DEVD_MSG_SIZE, M_CAMPERIPH, M_NOWAIT);
2139 if (sbmsg == NULL)
2140 return;
2141
2142 sbuf_new(&sb, sbmsg, CAM_PERIPH_DEVD_MSG_SIZE, SBUF_FIXEDLEN);
2143
2144 periph = xpt_path_periph(ccb->ccb_h.path);
2145 sbuf_printf(&sb, "device=%s%d ", periph->periph_name,
2146 periph->unit_number);
2147
2148 sbuf_printf(&sb, "serial=\"");
2149 if ((cgd = (struct ccb_getdev *)xpt_alloc_ccb_nowait()) != NULL) {
2150 xpt_setup_ccb(&cgd->ccb_h, ccb->ccb_h.path,
2151 CAM_PRIORITY_NORMAL);
2152 cgd->ccb_h.func_code = XPT_GDEV_TYPE;
2153 xpt_action((union ccb *)cgd);
2154
2155 if (cgd->ccb_h.status == CAM_REQ_CMP)
2156 sbuf_bcat(&sb, cgd->serial_num, cgd->serial_num_len);
2157 xpt_free_ccb((union ccb *)cgd);
2158 }
2159 sbuf_printf(&sb, "\" ");
2160 sbuf_printf(&sb, "cam_status=\"0x%x\" ", ccb->ccb_h.status);
2161
2162 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
2163 case CAM_CMD_TIMEOUT:
2164 sbuf_printf(&sb, "timeout=%d ", ccb->ccb_h.timeout);
2165 type = "timeout";
2166 break;
2167 case CAM_SCSI_STATUS_ERROR:
2168 sbuf_printf(&sb, "scsi_status=%d ", ccb->csio.scsi_status);
2169 if (scsi_extract_sense_ccb(ccb, &serr, &sk, &asc, &ascq))
2170 sbuf_printf(&sb, "scsi_sense=\"%02x %02x %02x %02x\" ",
2171 serr, sk, asc, ascq);
2172 type = "error";
2173 break;
2174 case CAM_ATA_STATUS_ERROR:
2175 sbuf_printf(&sb, "RES=\"");
2176 ata_res_sbuf(&ccb->ataio.res, &sb);
2177 sbuf_printf(&sb, "\" ");
2178 type = "error";
2179 break;
2180 default:
2181 type = "error";
2182 break;
2183 }
2184
2185 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2186 sbuf_printf(&sb, "CDB=\"");
2187 scsi_cdb_sbuf(scsiio_cdb_ptr(&ccb->csio), &sb);
2188 sbuf_printf(&sb, "\" ");
2189 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2190 sbuf_printf(&sb, "ACB=\"");
2191 ata_cmd_sbuf(&ccb->ataio.cmd, &sb);
2192 sbuf_printf(&sb, "\" ");
2193 }
2194
2195 if (sbuf_finish(&sb) == 0)
2196 devctl_notify("CAM", "periph", type, sbuf_data(&sb));
2197 sbuf_delete(&sb);
2198 free(sbmsg, M_CAMPERIPH);
2199 }
2200
2201 /*
2202 * Sysctl to force an invalidation of the drive right now. Can be
2203 * called with CTLFLAG_MPSAFE since we take periph lock.
2204 */
2205 int
cam_periph_invalidate_sysctl(SYSCTL_HANDLER_ARGS)2206 cam_periph_invalidate_sysctl(SYSCTL_HANDLER_ARGS)
2207 {
2208 struct cam_periph *periph;
2209 int error, value;
2210
2211 periph = arg1;
2212 value = 0;
2213 error = sysctl_handle_int(oidp, &value, 0, req);
2214 if (error != 0 || req->newptr == NULL || value != 1)
2215 return (error);
2216
2217 cam_periph_lock(periph);
2218 cam_periph_invalidate(periph);
2219 cam_periph_unlock(periph);
2220
2221 return (0);
2222 }
2223