GNU Linux-libre 4.9.337-gnu1
[releases.git] / drivers / scsi / device_handler / scsi_dh_alua.c
1 /*
2  * Generic SCSI-3 ALUA SCSI Device Handler
3  *
4  * Copyright (C) 2007-2010 Hannes Reinecke, SUSE Linux Products GmbH.
5  * All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  *
21  */
22 #include <linux/slab.h>
23 #include <linux/delay.h>
24 #include <linux/module.h>
25 #include <asm/unaligned.h>
26 #include <scsi/scsi.h>
27 #include <scsi/scsi_proto.h>
28 #include <scsi/scsi_dbg.h>
29 #include <scsi/scsi_eh.h>
30 #include <scsi/scsi_dh.h>
31
32 #define ALUA_DH_NAME "alua"
33 #define ALUA_DH_VER "2.0"
34
35 #define TPGS_SUPPORT_NONE               0x00
36 #define TPGS_SUPPORT_OPTIMIZED          0x01
37 #define TPGS_SUPPORT_NONOPTIMIZED       0x02
38 #define TPGS_SUPPORT_STANDBY            0x04
39 #define TPGS_SUPPORT_UNAVAILABLE        0x08
40 #define TPGS_SUPPORT_LBA_DEPENDENT      0x10
41 #define TPGS_SUPPORT_OFFLINE            0x40
42 #define TPGS_SUPPORT_TRANSITION         0x80
43
44 #define RTPG_FMT_MASK                   0x70
45 #define RTPG_FMT_EXT_HDR                0x10
46
47 #define TPGS_MODE_UNINITIALIZED          -1
48 #define TPGS_MODE_NONE                  0x0
49 #define TPGS_MODE_IMPLICIT              0x1
50 #define TPGS_MODE_EXPLICIT              0x2
51
52 #define ALUA_RTPG_SIZE                  128
53 #define ALUA_FAILOVER_TIMEOUT           60
54 #define ALUA_FAILOVER_RETRIES           5
55 #define ALUA_RTPG_DELAY_MSECS           5
56 #define ALUA_RTPG_RETRY_DELAY           2
57
58 /* device handler flags */
59 #define ALUA_OPTIMIZE_STPG              0x01
60 #define ALUA_RTPG_EXT_HDR_UNSUPP        0x02
61 #define ALUA_SYNC_STPG                  0x04
62 /* State machine flags */
63 #define ALUA_PG_RUN_RTPG                0x10
64 #define ALUA_PG_RUN_STPG                0x20
65 #define ALUA_PG_RUNNING                 0x40
66
67 static uint optimize_stpg;
68 module_param(optimize_stpg, uint, S_IRUGO|S_IWUSR);
69 MODULE_PARM_DESC(optimize_stpg, "Allow use of a non-optimized path, rather than sending a STPG, when implicit TPGS is supported (0=No,1=Yes). Default is 0.");
70
71 static LIST_HEAD(port_group_list);
72 static DEFINE_SPINLOCK(port_group_lock);
73 static struct workqueue_struct *kaluad_wq;
74 static struct workqueue_struct *kaluad_sync_wq;
75
76 struct alua_port_group {
77         struct kref             kref;
78         struct rcu_head         rcu;
79         struct list_head        node;
80         struct list_head        dh_list;
81         unsigned char           device_id_str[256];
82         int                     device_id_len;
83         int                     group_id;
84         int                     tpgs;
85         int                     state;
86         int                     pref;
87         unsigned                flags; /* used for optimizing STPG */
88         unsigned char           transition_tmo;
89         unsigned long           expiry;
90         unsigned long           interval;
91         struct delayed_work     rtpg_work;
92         spinlock_t              lock;
93         struct list_head        rtpg_list;
94         struct scsi_device      *rtpg_sdev;
95 };
96
97 struct alua_dh_data {
98         struct list_head        node;
99         struct alua_port_group  *pg;
100         int                     group_id;
101         spinlock_t              pg_lock;
102         struct scsi_device      *sdev;
103         int                     init_error;
104         struct mutex            init_mutex;
105 };
106
107 struct alua_queue_data {
108         struct list_head        entry;
109         activate_complete       callback_fn;
110         void                    *callback_data;
111 };
112
113 #define ALUA_POLICY_SWITCH_CURRENT      0
114 #define ALUA_POLICY_SWITCH_ALL          1
115
116 static void alua_rtpg_work(struct work_struct *work);
117 static bool alua_rtpg_queue(struct alua_port_group *pg,
118                             struct scsi_device *sdev,
119                             struct alua_queue_data *qdata, bool force);
120 static void alua_check(struct scsi_device *sdev, bool force);
121
122 static void release_port_group(struct kref *kref)
123 {
124         struct alua_port_group *pg;
125
126         pg = container_of(kref, struct alua_port_group, kref);
127         if (pg->rtpg_sdev)
128                 flush_delayed_work(&pg->rtpg_work);
129         spin_lock(&port_group_lock);
130         list_del(&pg->node);
131         spin_unlock(&port_group_lock);
132         kfree_rcu(pg, rcu);
133 }
134
135 /*
136  * submit_rtpg - Issue a REPORT TARGET GROUP STATES command
137  * @sdev: sdev the command should be sent to
138  */
139 static int submit_rtpg(struct scsi_device *sdev, unsigned char *buff,
140                        int bufflen, struct scsi_sense_hdr *sshdr, int flags)
141 {
142         u8 cdb[COMMAND_SIZE(MAINTENANCE_IN)];
143         int req_flags = REQ_FAILFAST_DEV | REQ_FAILFAST_TRANSPORT |
144                 REQ_FAILFAST_DRIVER;
145
146         /* Prepare the command. */
147         memset(cdb, 0x0, COMMAND_SIZE(MAINTENANCE_IN));
148         cdb[0] = MAINTENANCE_IN;
149         if (!(flags & ALUA_RTPG_EXT_HDR_UNSUPP))
150                 cdb[1] = MI_REPORT_TARGET_PGS | MI_EXT_HDR_PARAM_FMT;
151         else
152                 cdb[1] = MI_REPORT_TARGET_PGS;
153         put_unaligned_be32(bufflen, &cdb[6]);
154
155         return scsi_execute_req_flags(sdev, cdb, DMA_FROM_DEVICE,
156                                       buff, bufflen, sshdr,
157                                       ALUA_FAILOVER_TIMEOUT * HZ,
158                                       ALUA_FAILOVER_RETRIES, NULL, req_flags);
159 }
160
161 /*
162  * submit_stpg - Issue a SET TARGET PORT GROUP command
163  *
164  * Currently we're only setting the current target port group state
165  * to 'active/optimized' and let the array firmware figure out
166  * the states of the remaining groups.
167  */
168 static int submit_stpg(struct scsi_device *sdev, int group_id,
169                        struct scsi_sense_hdr *sshdr)
170 {
171         u8 cdb[COMMAND_SIZE(MAINTENANCE_OUT)];
172         unsigned char stpg_data[8];
173         int stpg_len = 8;
174         int req_flags = REQ_FAILFAST_DEV | REQ_FAILFAST_TRANSPORT |
175                 REQ_FAILFAST_DRIVER;
176
177         /* Prepare the data buffer */
178         memset(stpg_data, 0, stpg_len);
179         stpg_data[4] = SCSI_ACCESS_STATE_OPTIMAL;
180         put_unaligned_be16(group_id, &stpg_data[6]);
181
182         /* Prepare the command. */
183         memset(cdb, 0x0, COMMAND_SIZE(MAINTENANCE_OUT));
184         cdb[0] = MAINTENANCE_OUT;
185         cdb[1] = MO_SET_TARGET_PGS;
186         put_unaligned_be32(stpg_len, &cdb[6]);
187
188         return scsi_execute_req_flags(sdev, cdb, DMA_TO_DEVICE,
189                                       stpg_data, stpg_len,
190                                       sshdr, ALUA_FAILOVER_TIMEOUT * HZ,
191                                       ALUA_FAILOVER_RETRIES, NULL, req_flags);
192 }
193
194 static struct alua_port_group *alua_find_get_pg(char *id_str, size_t id_size,
195                                                 int group_id)
196 {
197         struct alua_port_group *pg;
198
199         if (!id_str || !id_size || !strlen(id_str))
200                 return NULL;
201
202         list_for_each_entry(pg, &port_group_list, node) {
203                 if (pg->group_id != group_id)
204                         continue;
205                 if (!pg->device_id_len || pg->device_id_len != id_size)
206                         continue;
207                 if (strncmp(pg->device_id_str, id_str, id_size))
208                         continue;
209                 if (!kref_get_unless_zero(&pg->kref))
210                         continue;
211                 return pg;
212         }
213
214         return NULL;
215 }
216
217 /*
218  * alua_alloc_pg - Allocate a new port_group structure
219  * @sdev: scsi device
220  * @h: alua device_handler data
221  * @group_id: port group id
222  *
223  * Allocate a new port_group structure for a given
224  * device.
225  */
226 static struct alua_port_group *alua_alloc_pg(struct scsi_device *sdev,
227                                              int group_id, int tpgs)
228 {
229         struct alua_port_group *pg, *tmp_pg;
230
231         pg = kzalloc(sizeof(struct alua_port_group), GFP_KERNEL);
232         if (!pg)
233                 return ERR_PTR(-ENOMEM);
234
235         pg->device_id_len = scsi_vpd_lun_id(sdev, pg->device_id_str,
236                                             sizeof(pg->device_id_str));
237         if (pg->device_id_len <= 0) {
238                 /*
239                  * TPGS supported but no device identification found.
240                  * Generate private device identification.
241                  */
242                 sdev_printk(KERN_INFO, sdev,
243                             "%s: No device descriptors found\n",
244                             ALUA_DH_NAME);
245                 pg->device_id_str[0] = '\0';
246                 pg->device_id_len = 0;
247         }
248         pg->group_id = group_id;
249         pg->tpgs = tpgs;
250         pg->state = SCSI_ACCESS_STATE_OPTIMAL;
251         if (optimize_stpg)
252                 pg->flags |= ALUA_OPTIMIZE_STPG;
253         kref_init(&pg->kref);
254         INIT_DELAYED_WORK(&pg->rtpg_work, alua_rtpg_work);
255         INIT_LIST_HEAD(&pg->rtpg_list);
256         INIT_LIST_HEAD(&pg->node);
257         INIT_LIST_HEAD(&pg->dh_list);
258         spin_lock_init(&pg->lock);
259
260         spin_lock(&port_group_lock);
261         tmp_pg = alua_find_get_pg(pg->device_id_str, pg->device_id_len,
262                                   group_id);
263         if (tmp_pg) {
264                 spin_unlock(&port_group_lock);
265                 kfree(pg);
266                 return tmp_pg;
267         }
268
269         list_add(&pg->node, &port_group_list);
270         spin_unlock(&port_group_lock);
271
272         return pg;
273 }
274
275 /*
276  * alua_check_tpgs - Evaluate TPGS setting
277  * @sdev: device to be checked
278  *
279  * Examine the TPGS setting of the sdev to find out if ALUA
280  * is supported.
281  */
282 static int alua_check_tpgs(struct scsi_device *sdev)
283 {
284         int tpgs = TPGS_MODE_NONE;
285
286         /*
287          * ALUA support for non-disk devices is fraught with
288          * difficulties, so disable it for now.
289          */
290         if (sdev->type != TYPE_DISK) {
291                 sdev_printk(KERN_INFO, sdev,
292                             "%s: disable for non-disk devices\n",
293                             ALUA_DH_NAME);
294                 return tpgs;
295         }
296
297         tpgs = scsi_device_tpgs(sdev);
298         switch (tpgs) {
299         case TPGS_MODE_EXPLICIT|TPGS_MODE_IMPLICIT:
300                 sdev_printk(KERN_INFO, sdev,
301                             "%s: supports implicit and explicit TPGS\n",
302                             ALUA_DH_NAME);
303                 break;
304         case TPGS_MODE_EXPLICIT:
305                 sdev_printk(KERN_INFO, sdev, "%s: supports explicit TPGS\n",
306                             ALUA_DH_NAME);
307                 break;
308         case TPGS_MODE_IMPLICIT:
309                 sdev_printk(KERN_INFO, sdev, "%s: supports implicit TPGS\n",
310                             ALUA_DH_NAME);
311                 break;
312         case TPGS_MODE_NONE:
313                 sdev_printk(KERN_INFO, sdev, "%s: not supported\n",
314                             ALUA_DH_NAME);
315                 break;
316         default:
317                 sdev_printk(KERN_INFO, sdev,
318                             "%s: unsupported TPGS setting %d\n",
319                             ALUA_DH_NAME, tpgs);
320                 tpgs = TPGS_MODE_NONE;
321                 break;
322         }
323
324         return tpgs;
325 }
326
327 /*
328  * alua_check_vpd - Evaluate INQUIRY vpd page 0x83
329  * @sdev: device to be checked
330  *
331  * Extract the relative target port and the target port group
332  * descriptor from the list of identificators.
333  */
334 static int alua_check_vpd(struct scsi_device *sdev, struct alua_dh_data *h,
335                           int tpgs)
336 {
337         int rel_port = -1, group_id;
338         struct alua_port_group *pg, *old_pg = NULL;
339         bool pg_updated = false;
340         unsigned long flags;
341
342         group_id = scsi_vpd_tpg_id(sdev, &rel_port);
343         if (group_id < 0) {
344                 /*
345                  * Internal error; TPGS supported but required
346                  * VPD identification descriptors not present.
347                  * Disable ALUA support
348                  */
349                 sdev_printk(KERN_INFO, sdev,
350                             "%s: No target port descriptors found\n",
351                             ALUA_DH_NAME);
352                 return SCSI_DH_DEV_UNSUPP;
353         }
354
355         pg = alua_alloc_pg(sdev, group_id, tpgs);
356         if (IS_ERR(pg)) {
357                 if (PTR_ERR(pg) == -ENOMEM)
358                         return SCSI_DH_NOMEM;
359                 return SCSI_DH_DEV_UNSUPP;
360         }
361         if (pg->device_id_len)
362                 sdev_printk(KERN_INFO, sdev,
363                             "%s: device %s port group %x rel port %x\n",
364                             ALUA_DH_NAME, pg->device_id_str,
365                             group_id, rel_port);
366         else
367                 sdev_printk(KERN_INFO, sdev,
368                             "%s: port group %x rel port %x\n",
369                             ALUA_DH_NAME, group_id, rel_port);
370
371         /* Check for existing port group references */
372         spin_lock(&h->pg_lock);
373         old_pg = h->pg;
374         if (old_pg != pg) {
375                 /* port group has changed. Update to new port group */
376                 if (h->pg) {
377                         spin_lock_irqsave(&old_pg->lock, flags);
378                         list_del_rcu(&h->node);
379                         spin_unlock_irqrestore(&old_pg->lock, flags);
380                 }
381                 rcu_assign_pointer(h->pg, pg);
382                 pg_updated = true;
383         }
384
385         spin_lock_irqsave(&pg->lock, flags);
386         if (sdev->synchronous_alua)
387                 pg->flags |= ALUA_SYNC_STPG;
388         if (pg_updated)
389                 list_add_rcu(&h->node, &pg->dh_list);
390         spin_unlock_irqrestore(&pg->lock, flags);
391
392         alua_rtpg_queue(h->pg, sdev, NULL, true);
393         spin_unlock(&h->pg_lock);
394
395         if (old_pg)
396                 kref_put(&old_pg->kref, release_port_group);
397
398         return SCSI_DH_OK;
399 }
400
401 static char print_alua_state(unsigned char state)
402 {
403         switch (state) {
404         case SCSI_ACCESS_STATE_OPTIMAL:
405                 return 'A';
406         case SCSI_ACCESS_STATE_ACTIVE:
407                 return 'N';
408         case SCSI_ACCESS_STATE_STANDBY:
409                 return 'S';
410         case SCSI_ACCESS_STATE_UNAVAILABLE:
411                 return 'U';
412         case SCSI_ACCESS_STATE_LBA:
413                 return 'L';
414         case SCSI_ACCESS_STATE_OFFLINE:
415                 return 'O';
416         case SCSI_ACCESS_STATE_TRANSITIONING:
417                 return 'T';
418         default:
419                 return 'X';
420         }
421 }
422
423 static int alua_check_sense(struct scsi_device *sdev,
424                             struct scsi_sense_hdr *sense_hdr)
425 {
426         switch (sense_hdr->sense_key) {
427         case NOT_READY:
428                 if (sense_hdr->asc == 0x04 && sense_hdr->ascq == 0x0a) {
429                         /*
430                          * LUN Not Accessible - ALUA state transition
431                          */
432                         alua_check(sdev, false);
433                         return NEEDS_RETRY;
434                 }
435                 break;
436         case UNIT_ATTENTION:
437                 if (sense_hdr->asc == 0x29 && sense_hdr->ascq == 0x00) {
438                         /*
439                          * Power On, Reset, or Bus Device Reset.
440                          * Might have obscured a state transition,
441                          * so schedule a recheck.
442                          */
443                         alua_check(sdev, true);
444                         return ADD_TO_MLQUEUE;
445                 }
446                 if (sense_hdr->asc == 0x29 && sense_hdr->ascq == 0x04)
447                         /*
448                          * Device internal reset
449                          */
450                         return ADD_TO_MLQUEUE;
451                 if (sense_hdr->asc == 0x2a && sense_hdr->ascq == 0x01)
452                         /*
453                          * Mode Parameters Changed
454                          */
455                         return ADD_TO_MLQUEUE;
456                 if (sense_hdr->asc == 0x2a && sense_hdr->ascq == 0x06) {
457                         /*
458                          * ALUA state changed
459                          */
460                         alua_check(sdev, true);
461                         return ADD_TO_MLQUEUE;
462                 }
463                 if (sense_hdr->asc == 0x2a && sense_hdr->ascq == 0x07) {
464                         /*
465                          * Implicit ALUA state transition failed
466                          */
467                         alua_check(sdev, true);
468                         return ADD_TO_MLQUEUE;
469                 }
470                 if (sense_hdr->asc == 0x3f && sense_hdr->ascq == 0x03)
471                         /*
472                          * Inquiry data has changed
473                          */
474                         return ADD_TO_MLQUEUE;
475                 if (sense_hdr->asc == 0x3f && sense_hdr->ascq == 0x0e)
476                         /*
477                          * REPORTED_LUNS_DATA_HAS_CHANGED is reported
478                          * when switching controllers on targets like
479                          * Intel Multi-Flex. We can just retry.
480                          */
481                         return ADD_TO_MLQUEUE;
482                 break;
483         }
484
485         return SCSI_RETURN_NOT_HANDLED;
486 }
487
488 /*
489  * alua_tur - Send a TEST UNIT READY
490  * @sdev: device to which the TEST UNIT READY command should be send
491  *
492  * Send a TEST UNIT READY to @sdev to figure out the device state
493  * Returns SCSI_DH_RETRY if the sense code is NOT READY/ALUA TRANSITIONING,
494  * SCSI_DH_OK if no error occurred, and SCSI_DH_IO otherwise.
495  */
496 static int alua_tur(struct scsi_device *sdev)
497 {
498         struct scsi_sense_hdr sense_hdr;
499         int retval;
500
501         retval = scsi_test_unit_ready(sdev, ALUA_FAILOVER_TIMEOUT * HZ,
502                                       ALUA_FAILOVER_RETRIES, &sense_hdr);
503         if (sense_hdr.sense_key == NOT_READY &&
504             sense_hdr.asc == 0x04 && sense_hdr.ascq == 0x0a)
505                 return SCSI_DH_RETRY;
506         else if (retval)
507                 return SCSI_DH_IO;
508         else
509                 return SCSI_DH_OK;
510 }
511
512 /*
513  * alua_rtpg - Evaluate REPORT TARGET GROUP STATES
514  * @sdev: the device to be evaluated.
515  *
516  * Evaluate the Target Port Group State.
517  * Returns SCSI_DH_DEV_OFFLINED if the path is
518  * found to be unusable.
519  */
520 static int alua_rtpg(struct scsi_device *sdev, struct alua_port_group *pg)
521 {
522         struct scsi_sense_hdr sense_hdr;
523         struct alua_port_group *tmp_pg;
524         int len, k, off, valid_states = 0, bufflen = ALUA_RTPG_SIZE;
525         unsigned char *desc, *buff;
526         unsigned err, retval;
527         unsigned int tpg_desc_tbl_off;
528         unsigned char orig_transition_tmo;
529         unsigned long flags;
530         bool transitioning_sense = false;
531
532         if (!pg->expiry) {
533                 unsigned long transition_tmo = ALUA_FAILOVER_TIMEOUT * HZ;
534
535                 if (pg->transition_tmo)
536                         transition_tmo = pg->transition_tmo * HZ;
537
538                 pg->expiry = round_jiffies_up(jiffies + transition_tmo);
539         }
540
541         buff = kzalloc(bufflen, GFP_KERNEL);
542         if (!buff)
543                 return SCSI_DH_DEV_TEMP_BUSY;
544
545  retry:
546         err = 0;
547         retval = submit_rtpg(sdev, buff, bufflen, &sense_hdr, pg->flags);
548
549         if (retval) {
550                 if (!scsi_sense_valid(&sense_hdr)) {
551                         sdev_printk(KERN_INFO, sdev,
552                                     "%s: rtpg failed, result %d\n",
553                                     ALUA_DH_NAME, retval);
554                         kfree(buff);
555                         if (driver_byte(retval) == DRIVER_ERROR)
556                                 return SCSI_DH_DEV_TEMP_BUSY;
557                         return SCSI_DH_IO;
558                 }
559
560                 /*
561                  * submit_rtpg() has failed on existing arrays
562                  * when requesting extended header info, and
563                  * the array doesn't support extended headers,
564                  * even though it shouldn't according to T10.
565                  * The retry without rtpg_ext_hdr_req set
566                  * handles this.
567                  * Note:  some arrays return a sense key of ILLEGAL_REQUEST
568                  * with ASC 00h if they don't support the extended header.
569                  */
570                 if (!(pg->flags & ALUA_RTPG_EXT_HDR_UNSUPP) &&
571                     sense_hdr.sense_key == ILLEGAL_REQUEST) {
572                         pg->flags |= ALUA_RTPG_EXT_HDR_UNSUPP;
573                         goto retry;
574                 }
575                 /*
576                  * If the array returns with 'ALUA state transition'
577                  * sense code here it cannot return RTPG data during
578                  * transition. So set the state to 'transitioning' directly.
579                  */
580                 if (sense_hdr.sense_key == NOT_READY &&
581                     sense_hdr.asc == 0x04 && sense_hdr.ascq == 0x0a) {
582                         transitioning_sense = true;
583                         goto skip_rtpg;
584                 }
585                 /*
586                  * Retry on any other UNIT ATTENTION occurred.
587                  */
588                 if (sense_hdr.sense_key == UNIT_ATTENTION)
589                         err = SCSI_DH_RETRY;
590                 if (err == SCSI_DH_RETRY &&
591                     pg->expiry != 0 && time_before(jiffies, pg->expiry)) {
592                         sdev_printk(KERN_ERR, sdev, "%s: rtpg retry\n",
593                                     ALUA_DH_NAME);
594                         scsi_print_sense_hdr(sdev, ALUA_DH_NAME, &sense_hdr);
595                         kfree(buff);
596                         return err;
597                 }
598                 sdev_printk(KERN_ERR, sdev, "%s: rtpg failed\n",
599                             ALUA_DH_NAME);
600                 scsi_print_sense_hdr(sdev, ALUA_DH_NAME, &sense_hdr);
601                 kfree(buff);
602                 pg->expiry = 0;
603                 return SCSI_DH_IO;
604         }
605
606         len = get_unaligned_be32(&buff[0]) + 4;
607
608         if (len > bufflen) {
609                 /* Resubmit with the correct length */
610                 kfree(buff);
611                 bufflen = len;
612                 buff = kmalloc(bufflen, GFP_KERNEL);
613                 if (!buff) {
614                         sdev_printk(KERN_WARNING, sdev,
615                                     "%s: kmalloc buffer failed\n",__func__);
616                         /* Temporary failure, bypass */
617                         pg->expiry = 0;
618                         return SCSI_DH_DEV_TEMP_BUSY;
619                 }
620                 goto retry;
621         }
622
623         orig_transition_tmo = pg->transition_tmo;
624         if ((buff[4] & RTPG_FMT_MASK) == RTPG_FMT_EXT_HDR && buff[5] != 0)
625                 pg->transition_tmo = buff[5];
626         else
627                 pg->transition_tmo = ALUA_FAILOVER_TIMEOUT;
628
629         if (orig_transition_tmo != pg->transition_tmo) {
630                 sdev_printk(KERN_INFO, sdev,
631                             "%s: transition timeout set to %d seconds\n",
632                             ALUA_DH_NAME, pg->transition_tmo);
633                 pg->expiry = jiffies + pg->transition_tmo * HZ;
634         }
635
636         if ((buff[4] & RTPG_FMT_MASK) == RTPG_FMT_EXT_HDR)
637                 tpg_desc_tbl_off = 8;
638         else
639                 tpg_desc_tbl_off = 4;
640
641         for (k = tpg_desc_tbl_off, desc = buff + tpg_desc_tbl_off;
642              k < len;
643              k += off, desc += off) {
644                 u16 group_id = get_unaligned_be16(&desc[2]);
645
646                 spin_lock_irqsave(&port_group_lock, flags);
647                 tmp_pg = alua_find_get_pg(pg->device_id_str, pg->device_id_len,
648                                           group_id);
649                 spin_unlock_irqrestore(&port_group_lock, flags);
650                 if (tmp_pg) {
651                         if (spin_trylock_irqsave(&tmp_pg->lock, flags)) {
652                                 if ((tmp_pg == pg) ||
653                                     !(tmp_pg->flags & ALUA_PG_RUNNING)) {
654                                         struct alua_dh_data *h;
655
656                                         tmp_pg->state = desc[0] & 0x0f;
657                                         tmp_pg->pref = desc[0] >> 7;
658                                         rcu_read_lock();
659                                         list_for_each_entry_rcu(h,
660                                                 &tmp_pg->dh_list, node) {
661                                                 if (!h->sdev)
662                                                         continue;
663                                                 h->sdev->access_state = desc[0];
664                                         }
665                                         rcu_read_unlock();
666                                 }
667                                 if (tmp_pg == pg)
668                                         valid_states = desc[1];
669                                 spin_unlock_irqrestore(&tmp_pg->lock, flags);
670                         }
671                         kref_put(&tmp_pg->kref, release_port_group);
672                 }
673                 off = 8 + (desc[7] * 4);
674         }
675
676  skip_rtpg:
677         spin_lock_irqsave(&pg->lock, flags);
678         if (transitioning_sense)
679                 pg->state = SCSI_ACCESS_STATE_TRANSITIONING;
680
681         sdev_printk(KERN_INFO, sdev,
682                     "%s: port group %02x state %c %s supports %c%c%c%c%c%c%c\n",
683                     ALUA_DH_NAME, pg->group_id, print_alua_state(pg->state),
684                     pg->pref ? "preferred" : "non-preferred",
685                     valid_states&TPGS_SUPPORT_TRANSITION?'T':'t',
686                     valid_states&TPGS_SUPPORT_OFFLINE?'O':'o',
687                     valid_states&TPGS_SUPPORT_LBA_DEPENDENT?'L':'l',
688                     valid_states&TPGS_SUPPORT_UNAVAILABLE?'U':'u',
689                     valid_states&TPGS_SUPPORT_STANDBY?'S':'s',
690                     valid_states&TPGS_SUPPORT_NONOPTIMIZED?'N':'n',
691                     valid_states&TPGS_SUPPORT_OPTIMIZED?'A':'a');
692
693         switch (pg->state) {
694         case SCSI_ACCESS_STATE_TRANSITIONING:
695                 if (time_before(jiffies, pg->expiry)) {
696                         /* State transition, retry */
697                         pg->interval = ALUA_RTPG_RETRY_DELAY;
698                         err = SCSI_DH_RETRY;
699                 } else {
700                         struct alua_dh_data *h;
701
702                         /* Transitioning time exceeded, set port to standby */
703                         err = SCSI_DH_IO;
704                         pg->state = SCSI_ACCESS_STATE_STANDBY;
705                         pg->expiry = 0;
706                         rcu_read_lock();
707                         list_for_each_entry_rcu(h, &pg->dh_list, node) {
708                                 if (!h->sdev)
709                                         continue;
710                                 h->sdev->access_state =
711                                         (pg->state & SCSI_ACCESS_STATE_MASK);
712                                 if (pg->pref)
713                                         h->sdev->access_state |=
714                                                 SCSI_ACCESS_STATE_PREFERRED;
715                         }
716                         rcu_read_unlock();
717                 }
718                 break;
719         case SCSI_ACCESS_STATE_OFFLINE:
720                 /* Path unusable */
721                 err = SCSI_DH_DEV_OFFLINED;
722                 pg->expiry = 0;
723                 break;
724         default:
725                 /* Useable path if active */
726                 err = SCSI_DH_OK;
727                 pg->expiry = 0;
728                 break;
729         }
730         spin_unlock_irqrestore(&pg->lock, flags);
731         kfree(buff);
732         return err;
733 }
734
735 /*
736  * alua_stpg - Issue a SET TARGET PORT GROUP command
737  *
738  * Issue a SET TARGET PORT GROUP command and evaluate the
739  * response. Returns SCSI_DH_RETRY per default to trigger
740  * a re-evaluation of the target group state or SCSI_DH_OK
741  * if no further action needs to be taken.
742  */
743 static unsigned alua_stpg(struct scsi_device *sdev, struct alua_port_group *pg)
744 {
745         int retval;
746         struct scsi_sense_hdr sense_hdr;
747
748         if (!(pg->tpgs & TPGS_MODE_EXPLICIT)) {
749                 /* Only implicit ALUA supported, retry */
750                 return SCSI_DH_RETRY;
751         }
752         switch (pg->state) {
753         case SCSI_ACCESS_STATE_OPTIMAL:
754                 return SCSI_DH_OK;
755         case SCSI_ACCESS_STATE_ACTIVE:
756                 if ((pg->flags & ALUA_OPTIMIZE_STPG) &&
757                     !pg->pref &&
758                     (pg->tpgs & TPGS_MODE_IMPLICIT))
759                         return SCSI_DH_OK;
760                 break;
761         case SCSI_ACCESS_STATE_STANDBY:
762         case SCSI_ACCESS_STATE_UNAVAILABLE:
763                 break;
764         case SCSI_ACCESS_STATE_OFFLINE:
765                 return SCSI_DH_IO;
766         case SCSI_ACCESS_STATE_TRANSITIONING:
767                 break;
768         default:
769                 sdev_printk(KERN_INFO, sdev,
770                             "%s: stpg failed, unhandled TPGS state %d",
771                             ALUA_DH_NAME, pg->state);
772                 return SCSI_DH_NOSYS;
773         }
774         retval = submit_stpg(sdev, pg->group_id, &sense_hdr);
775
776         if (retval) {
777                 if (!scsi_sense_valid(&sense_hdr)) {
778                         sdev_printk(KERN_INFO, sdev,
779                                     "%s: stpg failed, result %d",
780                                     ALUA_DH_NAME, retval);
781                         if (driver_byte(retval) == DRIVER_ERROR)
782                                 return SCSI_DH_DEV_TEMP_BUSY;
783                 } else {
784                         sdev_printk(KERN_INFO, sdev, "%s: stpg failed\n",
785                                     ALUA_DH_NAME);
786                         scsi_print_sense_hdr(sdev, ALUA_DH_NAME, &sense_hdr);
787                 }
788         }
789         /* Retry RTPG */
790         return SCSI_DH_RETRY;
791 }
792
793 static void alua_rtpg_work(struct work_struct *work)
794 {
795         struct alua_port_group *pg =
796                 container_of(work, struct alua_port_group, rtpg_work.work);
797         struct scsi_device *sdev;
798         LIST_HEAD(qdata_list);
799         int err = SCSI_DH_OK;
800         struct alua_queue_data *qdata, *tmp;
801         unsigned long flags;
802         struct workqueue_struct *alua_wq = kaluad_wq;
803
804         spin_lock_irqsave(&pg->lock, flags);
805         sdev = pg->rtpg_sdev;
806         if (!sdev) {
807                 WARN_ON(pg->flags & ALUA_PG_RUN_RTPG);
808                 WARN_ON(pg->flags & ALUA_PG_RUN_STPG);
809                 spin_unlock_irqrestore(&pg->lock, flags);
810                 kref_put(&pg->kref, release_port_group);
811                 return;
812         }
813         if (pg->flags & ALUA_SYNC_STPG)
814                 alua_wq = kaluad_sync_wq;
815         pg->flags |= ALUA_PG_RUNNING;
816         if (pg->flags & ALUA_PG_RUN_RTPG) {
817                 int state = pg->state;
818
819                 pg->flags &= ~ALUA_PG_RUN_RTPG;
820                 spin_unlock_irqrestore(&pg->lock, flags);
821                 if (state == SCSI_ACCESS_STATE_TRANSITIONING) {
822                         if (alua_tur(sdev) == SCSI_DH_RETRY) {
823                                 spin_lock_irqsave(&pg->lock, flags);
824                                 pg->flags &= ~ALUA_PG_RUNNING;
825                                 pg->flags |= ALUA_PG_RUN_RTPG;
826                                 if (!pg->interval)
827                                         pg->interval = ALUA_RTPG_RETRY_DELAY;
828                                 spin_unlock_irqrestore(&pg->lock, flags);
829                                 queue_delayed_work(alua_wq, &pg->rtpg_work,
830                                                    pg->interval * HZ);
831                                 return;
832                         }
833                         /* Send RTPG on failure or if TUR indicates SUCCESS */
834                 }
835                 err = alua_rtpg(sdev, pg);
836                 spin_lock_irqsave(&pg->lock, flags);
837                 if (err == SCSI_DH_RETRY || pg->flags & ALUA_PG_RUN_RTPG) {
838                         pg->flags &= ~ALUA_PG_RUNNING;
839                         if (!pg->interval && !(pg->flags & ALUA_PG_RUN_RTPG))
840                                 pg->interval = ALUA_RTPG_RETRY_DELAY;
841                         pg->flags |= ALUA_PG_RUN_RTPG;
842                         spin_unlock_irqrestore(&pg->lock, flags);
843                         queue_delayed_work(alua_wq, &pg->rtpg_work,
844                                            pg->interval * HZ);
845                         return;
846                 }
847                 if (err != SCSI_DH_OK)
848                         pg->flags &= ~ALUA_PG_RUN_STPG;
849         }
850         if (pg->flags & ALUA_PG_RUN_STPG) {
851                 pg->flags &= ~ALUA_PG_RUN_STPG;
852                 spin_unlock_irqrestore(&pg->lock, flags);
853                 err = alua_stpg(sdev, pg);
854                 spin_lock_irqsave(&pg->lock, flags);
855                 if (err == SCSI_DH_RETRY || pg->flags & ALUA_PG_RUN_RTPG) {
856                         pg->flags |= ALUA_PG_RUN_RTPG;
857                         pg->interval = 0;
858                         pg->flags &= ~ALUA_PG_RUNNING;
859                         spin_unlock_irqrestore(&pg->lock, flags);
860                         queue_delayed_work(alua_wq, &pg->rtpg_work,
861                                            pg->interval * HZ);
862                         return;
863                 }
864         }
865
866         list_splice_init(&pg->rtpg_list, &qdata_list);
867         pg->rtpg_sdev = NULL;
868         spin_unlock_irqrestore(&pg->lock, flags);
869
870         list_for_each_entry_safe(qdata, tmp, &qdata_list, entry) {
871                 list_del(&qdata->entry);
872                 if (qdata->callback_fn)
873                         qdata->callback_fn(qdata->callback_data, err);
874                 kfree(qdata);
875         }
876         spin_lock_irqsave(&pg->lock, flags);
877         pg->flags &= ~ALUA_PG_RUNNING;
878         spin_unlock_irqrestore(&pg->lock, flags);
879         scsi_device_put(sdev);
880         kref_put(&pg->kref, release_port_group);
881 }
882
883 /**
884  * alua_rtpg_queue() - cause RTPG to be submitted asynchronously
885  *
886  * Returns true if and only if alua_rtpg_work() will be called asynchronously.
887  * That function is responsible for calling @qdata->fn().
888  */
889 static bool alua_rtpg_queue(struct alua_port_group *pg,
890                             struct scsi_device *sdev,
891                             struct alua_queue_data *qdata, bool force)
892 {
893         int start_queue = 0;
894         unsigned long flags;
895         struct workqueue_struct *alua_wq = kaluad_wq;
896
897         if (!pg || scsi_device_get(sdev))
898                 return false;
899
900         spin_lock_irqsave(&pg->lock, flags);
901         if (qdata) {
902                 list_add_tail(&qdata->entry, &pg->rtpg_list);
903                 pg->flags |= ALUA_PG_RUN_STPG;
904                 force = true;
905         }
906         if (pg->rtpg_sdev == NULL) {
907                 pg->interval = 0;
908                 pg->flags |= ALUA_PG_RUN_RTPG;
909                 kref_get(&pg->kref);
910                 pg->rtpg_sdev = sdev;
911                 start_queue = 1;
912         } else if (!(pg->flags & ALUA_PG_RUN_RTPG) && force) {
913                 pg->flags |= ALUA_PG_RUN_RTPG;
914                 /* Do not queue if the worker is already running */
915                 if (!(pg->flags & ALUA_PG_RUNNING)) {
916                         kref_get(&pg->kref);
917                         start_queue = 1;
918                 }
919         }
920
921         if (pg->flags & ALUA_SYNC_STPG)
922                 alua_wq = kaluad_sync_wq;
923         spin_unlock_irqrestore(&pg->lock, flags);
924
925         if (start_queue) {
926                 if (queue_delayed_work(alua_wq, &pg->rtpg_work,
927                                 msecs_to_jiffies(ALUA_RTPG_DELAY_MSECS)))
928                         sdev = NULL;
929                 else
930                         kref_put(&pg->kref, release_port_group);
931         }
932         if (sdev)
933                 scsi_device_put(sdev);
934
935         return true;
936 }
937
938 /*
939  * alua_initialize - Initialize ALUA state
940  * @sdev: the device to be initialized
941  *
942  * For the prep_fn to work correctly we have
943  * to initialize the ALUA state for the device.
944  */
945 static int alua_initialize(struct scsi_device *sdev, struct alua_dh_data *h)
946 {
947         int err = SCSI_DH_DEV_UNSUPP, tpgs;
948
949         mutex_lock(&h->init_mutex);
950         tpgs = alua_check_tpgs(sdev);
951         if (tpgs != TPGS_MODE_NONE)
952                 err = alua_check_vpd(sdev, h, tpgs);
953         h->init_error = err;
954         mutex_unlock(&h->init_mutex);
955         return err;
956 }
957 /*
958  * alua_set_params - set/unset the optimize flag
959  * @sdev: device on the path to be activated
960  * params - parameters in the following format
961  *      "no_of_params\0param1\0param2\0param3\0...\0"
962  * For example, to set the flag pass the following parameters
963  * from multipath.conf
964  *     hardware_handler        "2 alua 1"
965  */
966 static int alua_set_params(struct scsi_device *sdev, const char *params)
967 {
968         struct alua_dh_data *h = sdev->handler_data;
969         struct alua_port_group __rcu *pg = NULL;
970         unsigned int optimize = 0, argc;
971         const char *p = params;
972         int result = SCSI_DH_OK;
973         unsigned long flags;
974
975         if ((sscanf(params, "%u", &argc) != 1) || (argc != 1))
976                 return -EINVAL;
977
978         while (*p++)
979                 ;
980         if ((sscanf(p, "%u", &optimize) != 1) || (optimize > 1))
981                 return -EINVAL;
982
983         rcu_read_lock();
984         pg = rcu_dereference(h->pg);
985         if (!pg) {
986                 rcu_read_unlock();
987                 return -ENXIO;
988         }
989         spin_lock_irqsave(&pg->lock, flags);
990         if (optimize)
991                 pg->flags |= ALUA_OPTIMIZE_STPG;
992         else
993                 pg->flags &= ~ALUA_OPTIMIZE_STPG;
994         spin_unlock_irqrestore(&pg->lock, flags);
995         rcu_read_unlock();
996
997         return result;
998 }
999
1000 /*
1001  * alua_activate - activate a path
1002  * @sdev: device on the path to be activated
1003  *
1004  * We're currently switching the port group to be activated only and
1005  * let the array figure out the rest.
1006  * There may be other arrays which require us to switch all port groups
1007  * based on a certain policy. But until we actually encounter them it
1008  * should be okay.
1009  */
1010 static int alua_activate(struct scsi_device *sdev,
1011                         activate_complete fn, void *data)
1012 {
1013         struct alua_dh_data *h = sdev->handler_data;
1014         int err = SCSI_DH_OK;
1015         struct alua_queue_data *qdata;
1016         struct alua_port_group __rcu *pg;
1017
1018         qdata = kzalloc(sizeof(*qdata), GFP_KERNEL);
1019         if (!qdata) {
1020                 err = SCSI_DH_RES_TEMP_UNAVAIL;
1021                 goto out;
1022         }
1023         qdata->callback_fn = fn;
1024         qdata->callback_data = data;
1025
1026         mutex_lock(&h->init_mutex);
1027         rcu_read_lock();
1028         pg = rcu_dereference(h->pg);
1029         if (!pg || !kref_get_unless_zero(&pg->kref)) {
1030                 rcu_read_unlock();
1031                 kfree(qdata);
1032                 err = h->init_error;
1033                 mutex_unlock(&h->init_mutex);
1034                 goto out;
1035         }
1036         rcu_read_unlock();
1037         mutex_unlock(&h->init_mutex);
1038
1039         if (alua_rtpg_queue(pg, sdev, qdata, true))
1040                 fn = NULL;
1041         else
1042                 err = SCSI_DH_DEV_OFFLINED;
1043         kref_put(&pg->kref, release_port_group);
1044 out:
1045         if (fn)
1046                 fn(data, err);
1047         return 0;
1048 }
1049
1050 /*
1051  * alua_check - check path status
1052  * @sdev: device on the path to be checked
1053  *
1054  * Check the device status
1055  */
1056 static void alua_check(struct scsi_device *sdev, bool force)
1057 {
1058         struct alua_dh_data *h = sdev->handler_data;
1059         struct alua_port_group *pg;
1060
1061         rcu_read_lock();
1062         pg = rcu_dereference(h->pg);
1063         if (!pg || !kref_get_unless_zero(&pg->kref)) {
1064                 rcu_read_unlock();
1065                 return;
1066         }
1067         rcu_read_unlock();
1068
1069         alua_rtpg_queue(pg, sdev, NULL, force);
1070         kref_put(&pg->kref, release_port_group);
1071 }
1072
1073 /*
1074  * alua_prep_fn - request callback
1075  *
1076  * Fail I/O to all paths not in state
1077  * active/optimized or active/non-optimized.
1078  */
1079 static int alua_prep_fn(struct scsi_device *sdev, struct request *req)
1080 {
1081         struct alua_dh_data *h = sdev->handler_data;
1082         struct alua_port_group __rcu *pg;
1083         unsigned char state = SCSI_ACCESS_STATE_OPTIMAL;
1084         int ret = BLKPREP_OK;
1085
1086         rcu_read_lock();
1087         pg = rcu_dereference(h->pg);
1088         if (pg)
1089                 state = pg->state;
1090         rcu_read_unlock();
1091         if (state == SCSI_ACCESS_STATE_TRANSITIONING)
1092                 ret = BLKPREP_DEFER;
1093         else if (state != SCSI_ACCESS_STATE_OPTIMAL &&
1094                  state != SCSI_ACCESS_STATE_ACTIVE &&
1095                  state != SCSI_ACCESS_STATE_LBA) {
1096                 ret = BLKPREP_KILL;
1097                 req->cmd_flags |= REQ_QUIET;
1098         }
1099         return ret;
1100
1101 }
1102
1103 static void alua_rescan(struct scsi_device *sdev)
1104 {
1105         struct alua_dh_data *h = sdev->handler_data;
1106
1107         alua_initialize(sdev, h);
1108 }
1109
1110 /*
1111  * alua_bus_attach - Attach device handler
1112  * @sdev: device to be attached to
1113  */
1114 static int alua_bus_attach(struct scsi_device *sdev)
1115 {
1116         struct alua_dh_data *h;
1117         int err, ret = -EINVAL;
1118
1119         h = kzalloc(sizeof(*h) , GFP_KERNEL);
1120         if (!h)
1121                 return -ENOMEM;
1122         spin_lock_init(&h->pg_lock);
1123         rcu_assign_pointer(h->pg, NULL);
1124         h->init_error = SCSI_DH_OK;
1125         h->sdev = sdev;
1126         INIT_LIST_HEAD(&h->node);
1127
1128         mutex_init(&h->init_mutex);
1129         err = alua_initialize(sdev, h);
1130         if (err == SCSI_DH_NOMEM)
1131                 ret = -ENOMEM;
1132         if (err != SCSI_DH_OK && err != SCSI_DH_DEV_OFFLINED)
1133                 goto failed;
1134
1135         sdev->handler_data = h;
1136         return 0;
1137 failed:
1138         kfree(h);
1139         return ret;
1140 }
1141
1142 /*
1143  * alua_bus_detach - Detach device handler
1144  * @sdev: device to be detached from
1145  */
1146 static void alua_bus_detach(struct scsi_device *sdev)
1147 {
1148         struct alua_dh_data *h = sdev->handler_data;
1149         struct alua_port_group *pg;
1150
1151         spin_lock(&h->pg_lock);
1152         pg = h->pg;
1153         rcu_assign_pointer(h->pg, NULL);
1154         spin_unlock(&h->pg_lock);
1155         if (pg) {
1156                 spin_lock_irq(&pg->lock);
1157                 list_del_rcu(&h->node);
1158                 spin_unlock_irq(&pg->lock);
1159                 kref_put(&pg->kref, release_port_group);
1160         }
1161         sdev->handler_data = NULL;
1162         synchronize_rcu();
1163         kfree(h);
1164 }
1165
1166 static struct scsi_device_handler alua_dh = {
1167         .name = ALUA_DH_NAME,
1168         .module = THIS_MODULE,
1169         .attach = alua_bus_attach,
1170         .detach = alua_bus_detach,
1171         .prep_fn = alua_prep_fn,
1172         .check_sense = alua_check_sense,
1173         .activate = alua_activate,
1174         .rescan = alua_rescan,
1175         .set_params = alua_set_params,
1176 };
1177
1178 static int __init alua_init(void)
1179 {
1180         int r;
1181
1182         kaluad_wq = alloc_workqueue("kaluad", WQ_MEM_RECLAIM, 0);
1183         if (!kaluad_wq) {
1184                 /* Temporary failure, bypass */
1185                 return SCSI_DH_DEV_TEMP_BUSY;
1186         }
1187         kaluad_sync_wq = create_workqueue("kaluad_sync");
1188         if (!kaluad_sync_wq) {
1189                 destroy_workqueue(kaluad_wq);
1190                 return SCSI_DH_DEV_TEMP_BUSY;
1191         }
1192         r = scsi_register_device_handler(&alua_dh);
1193         if (r != 0) {
1194                 printk(KERN_ERR "%s: Failed to register scsi device handler",
1195                         ALUA_DH_NAME);
1196                 destroy_workqueue(kaluad_sync_wq);
1197                 destroy_workqueue(kaluad_wq);
1198         }
1199         return r;
1200 }
1201
1202 static void __exit alua_exit(void)
1203 {
1204         scsi_unregister_device_handler(&alua_dh);
1205         destroy_workqueue(kaluad_sync_wq);
1206         destroy_workqueue(kaluad_wq);
1207 }
1208
1209 module_init(alua_init);
1210 module_exit(alua_exit);
1211
1212 MODULE_DESCRIPTION("DM Multipath ALUA support");
1213 MODULE_AUTHOR("Hannes Reinecke <hare@suse.de>");
1214 MODULE_LICENSE("GPL");
1215 MODULE_VERSION(ALUA_DH_VER);