]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/scsi/libiscsi.c
Merge git://git.kernel.org/pub/scm/linux/kernel/git/pkl/squashfs-linus
[karo-tx-linux.git] / drivers / scsi / libiscsi.c
1 /*
2  * iSCSI lib functions
3  *
4  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
5  * Copyright (C) 2004 - 2006 Mike Christie
6  * Copyright (C) 2004 - 2005 Dmitry Yusupov
7  * Copyright (C) 2004 - 2005 Alex Aizman
8  * maintained by open-iscsi@googlegroups.com
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  */
24 #include <linux/types.h>
25 #include <linux/kfifo.h>
26 #include <linux/delay.h>
27 #include <linux/log2.h>
28 #include <asm/unaligned.h>
29 #include <net/tcp.h>
30 #include <scsi/scsi_cmnd.h>
31 #include <scsi/scsi_device.h>
32 #include <scsi/scsi_eh.h>
33 #include <scsi/scsi_tcq.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi.h>
36 #include <scsi/iscsi_proto.h>
37 #include <scsi/scsi_transport.h>
38 #include <scsi/scsi_transport_iscsi.h>
39 #include <scsi/libiscsi.h>
40
41 static int iscsi_dbg_lib_conn;
42 module_param_named(debug_libiscsi_conn, iscsi_dbg_lib_conn, int,
43                    S_IRUGO | S_IWUSR);
44 MODULE_PARM_DESC(debug_libiscsi_conn,
45                  "Turn on debugging for connections in libiscsi module. "
46                  "Set to 1 to turn on, and zero to turn off. Default is off.");
47
48 static int iscsi_dbg_lib_session;
49 module_param_named(debug_libiscsi_session, iscsi_dbg_lib_session, int,
50                    S_IRUGO | S_IWUSR);
51 MODULE_PARM_DESC(debug_libiscsi_session,
52                  "Turn on debugging for sessions in libiscsi module. "
53                  "Set to 1 to turn on, and zero to turn off. Default is off.");
54
55 static int iscsi_dbg_lib_eh;
56 module_param_named(debug_libiscsi_eh, iscsi_dbg_lib_eh, int,
57                    S_IRUGO | S_IWUSR);
58 MODULE_PARM_DESC(debug_libiscsi_eh,
59                  "Turn on debugging for error handling in libiscsi module. "
60                  "Set to 1 to turn on, and zero to turn off. Default is off.");
61
62 #define ISCSI_DBG_CONN(_conn, dbg_fmt, arg...)                  \
63         do {                                                    \
64                 if (iscsi_dbg_lib_conn)                         \
65                         iscsi_conn_printk(KERN_INFO, _conn,     \
66                                              "%s " dbg_fmt,     \
67                                              __func__, ##arg);  \
68         } while (0);
69
70 #define ISCSI_DBG_SESSION(_session, dbg_fmt, arg...)                    \
71         do {                                                            \
72                 if (iscsi_dbg_lib_session)                              \
73                         iscsi_session_printk(KERN_INFO, _session,       \
74                                              "%s " dbg_fmt,             \
75                                              __func__, ##arg);          \
76         } while (0);
77
78 #define ISCSI_DBG_EH(_session, dbg_fmt, arg...)                         \
79         do {                                                            \
80                 if (iscsi_dbg_lib_eh)                                   \
81                         iscsi_session_printk(KERN_INFO, _session,       \
82                                              "%s " dbg_fmt,             \
83                                              __func__, ##arg);          \
84         } while (0);
85
86 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
87 #define SNA32_CHECK 2147483648UL
88
89 static int iscsi_sna_lt(u32 n1, u32 n2)
90 {
91         return n1 != n2 && ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) ||
92                             (n1 > n2 && (n2 - n1 < SNA32_CHECK)));
93 }
94
95 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
96 static int iscsi_sna_lte(u32 n1, u32 n2)
97 {
98         return n1 == n2 || ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) ||
99                             (n1 > n2 && (n2 - n1 < SNA32_CHECK)));
100 }
101
102 inline void iscsi_conn_queue_work(struct iscsi_conn *conn)
103 {
104         struct Scsi_Host *shost = conn->session->host;
105         struct iscsi_host *ihost = shost_priv(shost);
106
107         if (ihost->workq)
108                 queue_work(ihost->workq, &conn->xmitwork);
109 }
110 EXPORT_SYMBOL_GPL(iscsi_conn_queue_work);
111
112 static void __iscsi_update_cmdsn(struct iscsi_session *session,
113                                  uint32_t exp_cmdsn, uint32_t max_cmdsn)
114 {
115         /*
116          * standard specifies this check for when to update expected and
117          * max sequence numbers
118          */
119         if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1))
120                 return;
121
122         if (exp_cmdsn != session->exp_cmdsn &&
123             !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn))
124                 session->exp_cmdsn = exp_cmdsn;
125
126         if (max_cmdsn != session->max_cmdsn &&
127             !iscsi_sna_lt(max_cmdsn, session->max_cmdsn)) {
128                 session->max_cmdsn = max_cmdsn;
129                 /*
130                  * if the window closed with IO queued, then kick the
131                  * xmit thread
132                  */
133                 if (!list_empty(&session->leadconn->cmdqueue) ||
134                     !list_empty(&session->leadconn->mgmtqueue))
135                         iscsi_conn_queue_work(session->leadconn);
136         }
137 }
138
139 void iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr)
140 {
141         __iscsi_update_cmdsn(session, be32_to_cpu(hdr->exp_cmdsn),
142                              be32_to_cpu(hdr->max_cmdsn));
143 }
144 EXPORT_SYMBOL_GPL(iscsi_update_cmdsn);
145
146 /**
147  * iscsi_prep_data_out_pdu - initialize Data-Out
148  * @task: scsi command task
149  * @r2t: R2T info
150  * @hdr: iscsi data in pdu
151  *
152  * Notes:
153  *      Initialize Data-Out within this R2T sequence and finds
154  *      proper data_offset within this SCSI command.
155  *
156  *      This function is called with connection lock taken.
157  **/
158 void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t,
159                            struct iscsi_data *hdr)
160 {
161         struct iscsi_conn *conn = task->conn;
162         unsigned int left = r2t->data_length - r2t->sent;
163
164         task->hdr_len = sizeof(struct iscsi_data);
165
166         memset(hdr, 0, sizeof(struct iscsi_data));
167         hdr->ttt = r2t->ttt;
168         hdr->datasn = cpu_to_be32(r2t->datasn);
169         r2t->datasn++;
170         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
171         memcpy(hdr->lun, task->lun, sizeof(hdr->lun));
172         hdr->itt = task->hdr_itt;
173         hdr->exp_statsn = r2t->exp_statsn;
174         hdr->offset = cpu_to_be32(r2t->data_offset + r2t->sent);
175         if (left > conn->max_xmit_dlength) {
176                 hton24(hdr->dlength, conn->max_xmit_dlength);
177                 r2t->data_count = conn->max_xmit_dlength;
178                 hdr->flags = 0;
179         } else {
180                 hton24(hdr->dlength, left);
181                 r2t->data_count = left;
182                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
183         }
184         conn->dataout_pdus_cnt++;
185 }
186 EXPORT_SYMBOL_GPL(iscsi_prep_data_out_pdu);
187
188 static int iscsi_add_hdr(struct iscsi_task *task, unsigned len)
189 {
190         unsigned exp_len = task->hdr_len + len;
191
192         if (exp_len > task->hdr_max) {
193                 WARN_ON(1);
194                 return -EINVAL;
195         }
196
197         WARN_ON(len & (ISCSI_PAD_LEN - 1)); /* caller must pad the AHS */
198         task->hdr_len = exp_len;
199         return 0;
200 }
201
202 /*
203  * make an extended cdb AHS
204  */
205 static int iscsi_prep_ecdb_ahs(struct iscsi_task *task)
206 {
207         struct scsi_cmnd *cmd = task->sc;
208         unsigned rlen, pad_len;
209         unsigned short ahslength;
210         struct iscsi_ecdb_ahdr *ecdb_ahdr;
211         int rc;
212
213         ecdb_ahdr = iscsi_next_hdr(task);
214         rlen = cmd->cmd_len - ISCSI_CDB_SIZE;
215
216         BUG_ON(rlen > sizeof(ecdb_ahdr->ecdb));
217         ahslength = rlen + sizeof(ecdb_ahdr->reserved);
218
219         pad_len = iscsi_padding(rlen);
220
221         rc = iscsi_add_hdr(task, sizeof(ecdb_ahdr->ahslength) +
222                            sizeof(ecdb_ahdr->ahstype) + ahslength + pad_len);
223         if (rc)
224                 return rc;
225
226         if (pad_len)
227                 memset(&ecdb_ahdr->ecdb[rlen], 0, pad_len);
228
229         ecdb_ahdr->ahslength = cpu_to_be16(ahslength);
230         ecdb_ahdr->ahstype = ISCSI_AHSTYPE_CDB;
231         ecdb_ahdr->reserved = 0;
232         memcpy(ecdb_ahdr->ecdb, cmd->cmnd + ISCSI_CDB_SIZE, rlen);
233
234         ISCSI_DBG_SESSION(task->conn->session,
235                           "iscsi_prep_ecdb_ahs: varlen_cdb_len %d "
236                           "rlen %d pad_len %d ahs_length %d iscsi_headers_size "
237                           "%u\n", cmd->cmd_len, rlen, pad_len, ahslength,
238                           task->hdr_len);
239         return 0;
240 }
241
242 static int iscsi_prep_bidi_ahs(struct iscsi_task *task)
243 {
244         struct scsi_cmnd *sc = task->sc;
245         struct iscsi_rlength_ahdr *rlen_ahdr;
246         int rc;
247
248         rlen_ahdr = iscsi_next_hdr(task);
249         rc = iscsi_add_hdr(task, sizeof(*rlen_ahdr));
250         if (rc)
251                 return rc;
252
253         rlen_ahdr->ahslength =
254                 cpu_to_be16(sizeof(rlen_ahdr->read_length) +
255                                                   sizeof(rlen_ahdr->reserved));
256         rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH;
257         rlen_ahdr->reserved = 0;
258         rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length);
259
260         ISCSI_DBG_SESSION(task->conn->session,
261                           "bidi-in rlen_ahdr->read_length(%d) "
262                           "rlen_ahdr->ahslength(%d)\n",
263                           be32_to_cpu(rlen_ahdr->read_length),
264                           be16_to_cpu(rlen_ahdr->ahslength));
265         return 0;
266 }
267
268 /**
269  * iscsi_check_tmf_restrictions - check if a task is affected by TMF
270  * @task: iscsi task
271  * @opcode: opcode to check for
272  *
273  * During TMF a task has to be checked if it's affected.
274  * All unrelated I/O can be passed through, but I/O to the
275  * affected LUN should be restricted.
276  * If 'fast_abort' is set we won't be sending any I/O to the
277  * affected LUN.
278  * Otherwise the target is waiting for all TTTs to be completed,
279  * so we have to send all outstanding Data-Out PDUs to the target.
280  */
281 static int iscsi_check_tmf_restrictions(struct iscsi_task *task, int opcode)
282 {
283         struct iscsi_conn *conn = task->conn;
284         struct iscsi_tm *tmf = &conn->tmhdr;
285         unsigned int hdr_lun;
286
287         if (conn->tmf_state == TMF_INITIAL)
288                 return 0;
289
290         if ((tmf->opcode & ISCSI_OPCODE_MASK) != ISCSI_OP_SCSI_TMFUNC)
291                 return 0;
292
293         switch (ISCSI_TM_FUNC_VALUE(tmf)) {
294         case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
295                 /*
296                  * Allow PDUs for unrelated LUNs
297                  */
298                 hdr_lun = scsilun_to_int((struct scsi_lun *)tmf->lun);
299                 if (hdr_lun != task->sc->device->lun)
300                         return 0;
301                 /* fall through */
302         case ISCSI_TM_FUNC_TARGET_WARM_RESET:
303                 /*
304                  * Fail all SCSI cmd PDUs
305                  */
306                 if (opcode != ISCSI_OP_SCSI_DATA_OUT) {
307                         iscsi_conn_printk(KERN_INFO, conn,
308                                           "task [op %x/%x itt "
309                                           "0x%x/0x%x] "
310                                           "rejected.\n",
311                                           task->hdr->opcode, opcode,
312                                           task->itt, task->hdr_itt);
313                         return -EACCES;
314                 }
315                 /*
316                  * And also all data-out PDUs in response to R2T
317                  * if fast_abort is set.
318                  */
319                 if (conn->session->fast_abort) {
320                         iscsi_conn_printk(KERN_INFO, conn,
321                                           "task [op %x/%x itt "
322                                           "0x%x/0x%x] fast abort.\n",
323                                           task->hdr->opcode, opcode,
324                                           task->itt, task->hdr_itt);
325                         return -EACCES;
326                 }
327                 break;
328         case ISCSI_TM_FUNC_ABORT_TASK:
329                 /*
330                  * the caller has already checked if the task
331                  * they want to abort was in the pending queue so if
332                  * we are here the cmd pdu has gone out already, and
333                  * we will only hit this for data-outs
334                  */
335                 if (opcode == ISCSI_OP_SCSI_DATA_OUT &&
336                     task->hdr_itt == tmf->rtt) {
337                         ISCSI_DBG_SESSION(conn->session,
338                                           "Preventing task %x/%x from sending "
339                                           "data-out due to abort task in "
340                                           "progress\n", task->itt,
341                                           task->hdr_itt);
342                         return -EACCES;
343                 }
344                 break;
345         }
346
347         return 0;
348 }
349
350 /**
351  * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu
352  * @task: iscsi task
353  *
354  * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set
355  * fields like dlength or final based on how much data it sends
356  */
357 static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task)
358 {
359         struct iscsi_conn *conn = task->conn;
360         struct iscsi_session *session = conn->session;
361         struct scsi_cmnd *sc = task->sc;
362         struct iscsi_cmd *hdr;
363         unsigned hdrlength, cmd_len;
364         itt_t itt;
365         int rc;
366
367         rc = iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_CMD);
368         if (rc)
369                 return rc;
370
371         if (conn->session->tt->alloc_pdu) {
372                 rc = conn->session->tt->alloc_pdu(task, ISCSI_OP_SCSI_CMD);
373                 if (rc)
374                         return rc;
375         }
376         hdr = (struct iscsi_cmd *) task->hdr;
377         itt = hdr->itt;
378         memset(hdr, 0, sizeof(*hdr));
379
380         if (session->tt->parse_pdu_itt)
381                 hdr->itt = task->hdr_itt = itt;
382         else
383                 hdr->itt = task->hdr_itt = build_itt(task->itt,
384                                                      task->conn->session->age);
385         task->hdr_len = 0;
386         rc = iscsi_add_hdr(task, sizeof(*hdr));
387         if (rc)
388                 return rc;
389         hdr->opcode = ISCSI_OP_SCSI_CMD;
390         hdr->flags = ISCSI_ATTR_SIMPLE;
391         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
392         memcpy(task->lun, hdr->lun, sizeof(task->lun));
393         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
394         cmd_len = sc->cmd_len;
395         if (cmd_len < ISCSI_CDB_SIZE)
396                 memset(&hdr->cdb[cmd_len], 0, ISCSI_CDB_SIZE - cmd_len);
397         else if (cmd_len > ISCSI_CDB_SIZE) {
398                 rc = iscsi_prep_ecdb_ahs(task);
399                 if (rc)
400                         return rc;
401                 cmd_len = ISCSI_CDB_SIZE;
402         }
403         memcpy(hdr->cdb, sc->cmnd, cmd_len);
404
405         task->imm_count = 0;
406         if (scsi_bidi_cmnd(sc)) {
407                 hdr->flags |= ISCSI_FLAG_CMD_READ;
408                 rc = iscsi_prep_bidi_ahs(task);
409                 if (rc)
410                         return rc;
411         }
412         if (sc->sc_data_direction == DMA_TO_DEVICE) {
413                 unsigned out_len = scsi_out(sc)->length;
414                 struct iscsi_r2t_info *r2t = &task->unsol_r2t;
415
416                 hdr->data_length = cpu_to_be32(out_len);
417                 hdr->flags |= ISCSI_FLAG_CMD_WRITE;
418                 /*
419                  * Write counters:
420                  *
421                  *      imm_count       bytes to be sent right after
422                  *                      SCSI PDU Header
423                  *
424                  *      unsol_count     bytes(as Data-Out) to be sent
425                  *                      without R2T ack right after
426                  *                      immediate data
427                  *
428                  *      r2t data_length bytes to be sent via R2T ack's
429                  *
430                  *      pad_count       bytes to be sent as zero-padding
431                  */
432                 memset(r2t, 0, sizeof(*r2t));
433
434                 if (session->imm_data_en) {
435                         if (out_len >= session->first_burst)
436                                 task->imm_count = min(session->first_burst,
437                                                         conn->max_xmit_dlength);
438                         else
439                                 task->imm_count = min(out_len,
440                                                         conn->max_xmit_dlength);
441                         hton24(hdr->dlength, task->imm_count);
442                 } else
443                         zero_data(hdr->dlength);
444
445                 if (!session->initial_r2t_en) {
446                         r2t->data_length = min(session->first_burst, out_len) -
447                                                task->imm_count;
448                         r2t->data_offset = task->imm_count;
449                         r2t->ttt = cpu_to_be32(ISCSI_RESERVED_TAG);
450                         r2t->exp_statsn = cpu_to_be32(conn->exp_statsn);
451                 }
452
453                 if (!task->unsol_r2t.data_length)
454                         /* No unsolicit Data-Out's */
455                         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
456         } else {
457                 hdr->flags |= ISCSI_FLAG_CMD_FINAL;
458                 zero_data(hdr->dlength);
459                 hdr->data_length = cpu_to_be32(scsi_in(sc)->length);
460
461                 if (sc->sc_data_direction == DMA_FROM_DEVICE)
462                         hdr->flags |= ISCSI_FLAG_CMD_READ;
463         }
464
465         /* calculate size of additional header segments (AHSs) */
466         hdrlength = task->hdr_len - sizeof(*hdr);
467
468         WARN_ON(hdrlength & (ISCSI_PAD_LEN-1));
469         hdrlength /= ISCSI_PAD_LEN;
470
471         WARN_ON(hdrlength >= 256);
472         hdr->hlength = hdrlength & 0xFF;
473
474         if (session->tt->init_task && session->tt->init_task(task))
475                 return -EIO;
476
477         task->state = ISCSI_TASK_RUNNING;
478         hdr->cmdsn = task->cmdsn = cpu_to_be32(session->cmdsn);
479         session->cmdsn++;
480
481         conn->scsicmd_pdus_cnt++;
482         ISCSI_DBG_SESSION(session, "iscsi prep [%s cid %d sc %p cdb 0x%x "
483                           "itt 0x%x len %d bidi_len %d cmdsn %d win %d]\n",
484                           scsi_bidi_cmnd(sc) ? "bidirectional" :
485                           sc->sc_data_direction == DMA_TO_DEVICE ?
486                           "write" : "read", conn->id, sc, sc->cmnd[0],
487                           task->itt, scsi_bufflen(sc),
488                           scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0,
489                           session->cmdsn,
490                           session->max_cmdsn - session->exp_cmdsn + 1);
491         return 0;
492 }
493
494 /**
495  * iscsi_free_task - free a task
496  * @task: iscsi cmd task
497  *
498  * Must be called with session lock.
499  * This function returns the scsi command to scsi-ml or cleans
500  * up mgmt tasks then returns the task to the pool.
501  */
502 static void iscsi_free_task(struct iscsi_task *task)
503 {
504         struct iscsi_conn *conn = task->conn;
505         struct iscsi_session *session = conn->session;
506         struct scsi_cmnd *sc = task->sc;
507
508         ISCSI_DBG_SESSION(session, "freeing task itt 0x%x state %d sc %p\n",
509                           task->itt, task->state, task->sc);
510
511         session->tt->cleanup_task(task);
512         task->state = ISCSI_TASK_FREE;
513         task->sc = NULL;
514         /*
515          * login task is preallocated so do not free
516          */
517         if (conn->login_task == task)
518                 return;
519
520         kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*));
521
522         if (sc) {
523                 task->sc = NULL;
524                 /* SCSI eh reuses commands to verify us */
525                 sc->SCp.ptr = NULL;
526                 /*
527                  * queue command may call this to free the task, but
528                  * not have setup the sc callback
529                  */
530                 if (sc->scsi_done)
531                         sc->scsi_done(sc);
532         }
533 }
534
535 void __iscsi_get_task(struct iscsi_task *task)
536 {
537         atomic_inc(&task->refcount);
538 }
539 EXPORT_SYMBOL_GPL(__iscsi_get_task);
540
541 static void __iscsi_put_task(struct iscsi_task *task)
542 {
543         if (atomic_dec_and_test(&task->refcount))
544                 iscsi_free_task(task);
545 }
546
547 void iscsi_put_task(struct iscsi_task *task)
548 {
549         struct iscsi_session *session = task->conn->session;
550
551         spin_lock_bh(&session->lock);
552         __iscsi_put_task(task);
553         spin_unlock_bh(&session->lock);
554 }
555 EXPORT_SYMBOL_GPL(iscsi_put_task);
556
557 /**
558  * iscsi_complete_task - finish a task
559  * @task: iscsi cmd task
560  * @state: state to complete task with
561  *
562  * Must be called with session lock.
563  */
564 static void iscsi_complete_task(struct iscsi_task *task, int state)
565 {
566         struct iscsi_conn *conn = task->conn;
567
568         ISCSI_DBG_SESSION(conn->session,
569                           "complete task itt 0x%x state %d sc %p\n",
570                           task->itt, task->state, task->sc);
571         if (task->state == ISCSI_TASK_COMPLETED ||
572             task->state == ISCSI_TASK_ABRT_TMF ||
573             task->state == ISCSI_TASK_ABRT_SESS_RECOV)
574                 return;
575         WARN_ON_ONCE(task->state == ISCSI_TASK_FREE);
576         task->state = state;
577
578         if (!list_empty(&task->running))
579                 list_del_init(&task->running);
580
581         if (conn->task == task)
582                 conn->task = NULL;
583
584         if (conn->ping_task == task)
585                 conn->ping_task = NULL;
586
587         /* release get from queueing */
588         __iscsi_put_task(task);
589 }
590
591 /**
592  * iscsi_complete_scsi_task - finish scsi task normally
593  * @task: iscsi task for scsi cmd
594  * @exp_cmdsn: expected cmd sn in cpu format
595  * @max_cmdsn: max cmd sn in cpu format
596  *
597  * This is used when drivers do not need or cannot perform
598  * lower level pdu processing.
599  *
600  * Called with session lock
601  */
602 void iscsi_complete_scsi_task(struct iscsi_task *task,
603                               uint32_t exp_cmdsn, uint32_t max_cmdsn)
604 {
605         struct iscsi_conn *conn = task->conn;
606
607         ISCSI_DBG_SESSION(conn->session, "[itt 0x%x]\n", task->itt);
608
609         conn->last_recv = jiffies;
610         __iscsi_update_cmdsn(conn->session, exp_cmdsn, max_cmdsn);
611         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
612 }
613 EXPORT_SYMBOL_GPL(iscsi_complete_scsi_task);
614
615
616 /*
617  * session lock must be held and if not called for a task that is
618  * still pending or from the xmit thread, then xmit thread must
619  * be suspended.
620  */
621 static void fail_scsi_task(struct iscsi_task *task, int err)
622 {
623         struct iscsi_conn *conn = task->conn;
624         struct scsi_cmnd *sc;
625         int state;
626
627         /*
628          * if a command completes and we get a successful tmf response
629          * we will hit this because the scsi eh abort code does not take
630          * a ref to the task.
631          */
632         sc = task->sc;
633         if (!sc)
634                 return;
635
636         if (task->state == ISCSI_TASK_PENDING) {
637                 /*
638                  * cmd never made it to the xmit thread, so we should not count
639                  * the cmd in the sequencing
640                  */
641                 conn->session->queued_cmdsn--;
642                 /* it was never sent so just complete like normal */
643                 state = ISCSI_TASK_COMPLETED;
644         } else if (err == DID_TRANSPORT_DISRUPTED)
645                 state = ISCSI_TASK_ABRT_SESS_RECOV;
646         else
647                 state = ISCSI_TASK_ABRT_TMF;
648
649         sc->result = err << 16;
650         if (!scsi_bidi_cmnd(sc))
651                 scsi_set_resid(sc, scsi_bufflen(sc));
652         else {
653                 scsi_out(sc)->resid = scsi_out(sc)->length;
654                 scsi_in(sc)->resid = scsi_in(sc)->length;
655         }
656
657         iscsi_complete_task(task, state);
658 }
659
660 static int iscsi_prep_mgmt_task(struct iscsi_conn *conn,
661                                 struct iscsi_task *task)
662 {
663         struct iscsi_session *session = conn->session;
664         struct iscsi_hdr *hdr = task->hdr;
665         struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr;
666         uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK;
667
668         if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
669                 return -ENOTCONN;
670
671         if (opcode != ISCSI_OP_LOGIN && opcode != ISCSI_OP_TEXT)
672                 nop->exp_statsn = cpu_to_be32(conn->exp_statsn);
673         /*
674          * pre-format CmdSN for outgoing PDU.
675          */
676         nop->cmdsn = cpu_to_be32(session->cmdsn);
677         if (hdr->itt != RESERVED_ITT) {
678                 /*
679                  * TODO: We always use immediate for normal session pdus.
680                  * If we start to send tmfs or nops as non-immediate then
681                  * we should start checking the cmdsn numbers for mgmt tasks.
682                  *
683                  * During discovery sessions iscsid sends TEXT as non immediate,
684                  * but we always only send one PDU at a time.
685                  */
686                 if (conn->c_stage == ISCSI_CONN_STARTED &&
687                     !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
688                         session->queued_cmdsn++;
689                         session->cmdsn++;
690                 }
691         }
692
693         if (session->tt->init_task && session->tt->init_task(task))
694                 return -EIO;
695
696         if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT)
697                 session->state = ISCSI_STATE_LOGGING_OUT;
698
699         task->state = ISCSI_TASK_RUNNING;
700         ISCSI_DBG_SESSION(session, "mgmtpdu [op 0x%x hdr->itt 0x%x "
701                           "datalen %d]\n", hdr->opcode & ISCSI_OPCODE_MASK,
702                           hdr->itt, task->data_count);
703         return 0;
704 }
705
706 static struct iscsi_task *
707 __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
708                       char *data, uint32_t data_size)
709 {
710         struct iscsi_session *session = conn->session;
711         struct iscsi_host *ihost = shost_priv(session->host);
712         uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK;
713         struct iscsi_task *task;
714         itt_t itt;
715
716         if (session->state == ISCSI_STATE_TERMINATE)
717                 return NULL;
718
719         if (opcode == ISCSI_OP_LOGIN || opcode == ISCSI_OP_TEXT) {
720                 /*
721                  * Login and Text are sent serially, in
722                  * request-followed-by-response sequence.
723                  * Same task can be used. Same ITT must be used.
724                  * Note that login_task is preallocated at conn_create().
725                  */
726                 if (conn->login_task->state != ISCSI_TASK_FREE) {
727                         iscsi_conn_printk(KERN_ERR, conn, "Login/Text in "
728                                           "progress. Cannot start new task.\n");
729                         return NULL;
730                 }
731
732                 task = conn->login_task;
733         } else {
734                 if (session->state != ISCSI_STATE_LOGGED_IN)
735                         return NULL;
736
737                 BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE);
738                 BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED);
739
740                 if (!kfifo_out(&session->cmdpool.queue,
741                                  (void*)&task, sizeof(void*)))
742                         return NULL;
743         }
744         /*
745          * released in complete pdu for task we expect a response for, and
746          * released by the lld when it has transmitted the task for
747          * pdus we do not expect a response for.
748          */
749         atomic_set(&task->refcount, 1);
750         task->conn = conn;
751         task->sc = NULL;
752         INIT_LIST_HEAD(&task->running);
753         task->state = ISCSI_TASK_PENDING;
754
755         if (data_size) {
756                 memcpy(task->data, data, data_size);
757                 task->data_count = data_size;
758         } else
759                 task->data_count = 0;
760
761         if (conn->session->tt->alloc_pdu) {
762                 if (conn->session->tt->alloc_pdu(task, hdr->opcode)) {
763                         iscsi_conn_printk(KERN_ERR, conn, "Could not allocate "
764                                          "pdu for mgmt task.\n");
765                         goto free_task;
766                 }
767         }
768
769         itt = task->hdr->itt;
770         task->hdr_len = sizeof(struct iscsi_hdr);
771         memcpy(task->hdr, hdr, sizeof(struct iscsi_hdr));
772
773         if (hdr->itt != RESERVED_ITT) {
774                 if (session->tt->parse_pdu_itt)
775                         task->hdr->itt = itt;
776                 else
777                         task->hdr->itt = build_itt(task->itt,
778                                                    task->conn->session->age);
779         }
780
781         if (!ihost->workq) {
782                 if (iscsi_prep_mgmt_task(conn, task))
783                         goto free_task;
784
785                 if (session->tt->xmit_task(task))
786                         goto free_task;
787         } else {
788                 list_add_tail(&task->running, &conn->mgmtqueue);
789                 iscsi_conn_queue_work(conn);
790         }
791
792         return task;
793
794 free_task:
795         __iscsi_put_task(task);
796         return NULL;
797 }
798
799 int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr,
800                         char *data, uint32_t data_size)
801 {
802         struct iscsi_conn *conn = cls_conn->dd_data;
803         struct iscsi_session *session = conn->session;
804         int err = 0;
805
806         spin_lock_bh(&session->lock);
807         if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size))
808                 err = -EPERM;
809         spin_unlock_bh(&session->lock);
810         return err;
811 }
812 EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu);
813
814 /**
815  * iscsi_cmd_rsp - SCSI Command Response processing
816  * @conn: iscsi connection
817  * @hdr: iscsi header
818  * @task: scsi command task
819  * @data: cmd data buffer
820  * @datalen: len of buffer
821  *
822  * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and
823  * then completes the command and task.
824  **/
825 static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
826                                struct iscsi_task *task, char *data,
827                                int datalen)
828 {
829         struct iscsi_cmd_rsp *rhdr = (struct iscsi_cmd_rsp *)hdr;
830         struct iscsi_session *session = conn->session;
831         struct scsi_cmnd *sc = task->sc;
832
833         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
834         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
835
836         sc->result = (DID_OK << 16) | rhdr->cmd_status;
837
838         if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) {
839                 sc->result = DID_ERROR << 16;
840                 goto out;
841         }
842
843         if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) {
844                 uint16_t senselen;
845
846                 if (datalen < 2) {
847 invalid_datalen:
848                         iscsi_conn_printk(KERN_ERR,  conn,
849                                          "Got CHECK_CONDITION but invalid data "
850                                          "buffer size of %d\n", datalen);
851                         sc->result = DID_BAD_TARGET << 16;
852                         goto out;
853                 }
854
855                 senselen = get_unaligned_be16(data);
856                 if (datalen < senselen)
857                         goto invalid_datalen;
858
859                 memcpy(sc->sense_buffer, data + 2,
860                        min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
861                 ISCSI_DBG_SESSION(session, "copied %d bytes of sense\n",
862                                   min_t(uint16_t, senselen,
863                                   SCSI_SENSE_BUFFERSIZE));
864         }
865
866         if (rhdr->flags & (ISCSI_FLAG_CMD_BIDI_UNDERFLOW |
867                            ISCSI_FLAG_CMD_BIDI_OVERFLOW)) {
868                 int res_count = be32_to_cpu(rhdr->bi_residual_count);
869
870                 if (scsi_bidi_cmnd(sc) && res_count > 0 &&
871                                 (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW ||
872                                  res_count <= scsi_in(sc)->length))
873                         scsi_in(sc)->resid = res_count;
874                 else
875                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
876         }
877
878         if (rhdr->flags & (ISCSI_FLAG_CMD_UNDERFLOW |
879                            ISCSI_FLAG_CMD_OVERFLOW)) {
880                 int res_count = be32_to_cpu(rhdr->residual_count);
881
882                 if (res_count > 0 &&
883                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
884                      res_count <= scsi_bufflen(sc)))
885                         /* write side for bidi or uni-io set_resid */
886                         scsi_set_resid(sc, res_count);
887                 else
888                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
889         }
890 out:
891         ISCSI_DBG_SESSION(session, "cmd rsp done [sc %p res %d itt 0x%x]\n",
892                           sc, sc->result, task->itt);
893         conn->scsirsp_pdus_cnt++;
894         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
895 }
896
897 /**
898  * iscsi_data_in_rsp - SCSI Data-In Response processing
899  * @conn: iscsi connection
900  * @hdr:  iscsi pdu
901  * @task: scsi command task
902  **/
903 static void
904 iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
905                   struct iscsi_task *task)
906 {
907         struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)hdr;
908         struct scsi_cmnd *sc = task->sc;
909
910         if (!(rhdr->flags & ISCSI_FLAG_DATA_STATUS))
911                 return;
912
913         iscsi_update_cmdsn(conn->session, (struct iscsi_nopin *)hdr);
914         sc->result = (DID_OK << 16) | rhdr->cmd_status;
915         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
916         if (rhdr->flags & (ISCSI_FLAG_DATA_UNDERFLOW |
917                            ISCSI_FLAG_DATA_OVERFLOW)) {
918                 int res_count = be32_to_cpu(rhdr->residual_count);
919
920                 if (res_count > 0 &&
921                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
922                      res_count <= scsi_in(sc)->length))
923                         scsi_in(sc)->resid = res_count;
924                 else
925                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
926         }
927
928         ISCSI_DBG_SESSION(conn->session, "data in with status done "
929                           "[sc %p res %d itt 0x%x]\n",
930                           sc, sc->result, task->itt);
931         conn->scsirsp_pdus_cnt++;
932         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
933 }
934
935 static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr)
936 {
937         struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr;
938
939         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
940         conn->tmfrsp_pdus_cnt++;
941
942         if (conn->tmf_state != TMF_QUEUED)
943                 return;
944
945         if (tmf->response == ISCSI_TMF_RSP_COMPLETE)
946                 conn->tmf_state = TMF_SUCCESS;
947         else if (tmf->response == ISCSI_TMF_RSP_NO_TASK)
948                 conn->tmf_state = TMF_NOT_FOUND;
949         else
950                 conn->tmf_state = TMF_FAILED;
951         wake_up(&conn->ehwait);
952 }
953
954 static void iscsi_send_nopout(struct iscsi_conn *conn, struct iscsi_nopin *rhdr)
955 {
956         struct iscsi_nopout hdr;
957         struct iscsi_task *task;
958
959         if (!rhdr && conn->ping_task)
960                 return;
961
962         memset(&hdr, 0, sizeof(struct iscsi_nopout));
963         hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE;
964         hdr.flags = ISCSI_FLAG_CMD_FINAL;
965
966         if (rhdr) {
967                 memcpy(hdr.lun, rhdr->lun, 8);
968                 hdr.ttt = rhdr->ttt;
969                 hdr.itt = RESERVED_ITT;
970         } else
971                 hdr.ttt = RESERVED_ITT;
972
973         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)&hdr, NULL, 0);
974         if (!task)
975                 iscsi_conn_printk(KERN_ERR, conn, "Could not send nopout\n");
976         else if (!rhdr) {
977                 /* only track our nops */
978                 conn->ping_task = task;
979                 conn->last_ping = jiffies;
980         }
981 }
982
983 static int iscsi_nop_out_rsp(struct iscsi_task *task,
984                              struct iscsi_nopin *nop, char *data, int datalen)
985 {
986         struct iscsi_conn *conn = task->conn;
987         int rc = 0;
988
989         if (conn->ping_task != task) {
990                 /*
991                  * If this is not in response to one of our
992                  * nops then it must be from userspace.
993                  */
994                 if (iscsi_recv_pdu(conn->cls_conn, (struct iscsi_hdr *)nop,
995                                    data, datalen))
996                         rc = ISCSI_ERR_CONN_FAILED;
997         } else
998                 mod_timer(&conn->transport_timer, jiffies + conn->recv_timeout);
999         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1000         return rc;
1001 }
1002
1003 static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1004                                char *data, int datalen)
1005 {
1006         struct iscsi_reject *reject = (struct iscsi_reject *)hdr;
1007         struct iscsi_hdr rejected_pdu;
1008         int opcode, rc = 0;
1009
1010         conn->exp_statsn = be32_to_cpu(reject->statsn) + 1;
1011
1012         if (ntoh24(reject->dlength) > datalen ||
1013             ntoh24(reject->dlength) < sizeof(struct iscsi_hdr)) {
1014                 iscsi_conn_printk(KERN_ERR, conn, "Cannot handle rejected "
1015                                   "pdu. Invalid data length (pdu dlength "
1016                                   "%u, datalen %d\n", ntoh24(reject->dlength),
1017                                   datalen);
1018                 return ISCSI_ERR_PROTO;
1019         }
1020         memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr));
1021         opcode = rejected_pdu.opcode & ISCSI_OPCODE_MASK;
1022
1023         switch (reject->reason) {
1024         case ISCSI_REASON_DATA_DIGEST_ERROR:
1025                 iscsi_conn_printk(KERN_ERR, conn,
1026                                   "pdu (op 0x%x itt 0x%x) rejected "
1027                                   "due to DataDigest error.\n",
1028                                   rejected_pdu.itt, opcode);
1029                 break;
1030         case ISCSI_REASON_IMM_CMD_REJECT:
1031                 iscsi_conn_printk(KERN_ERR, conn,
1032                                   "pdu (op 0x%x itt 0x%x) rejected. Too many "
1033                                   "immediate commands.\n",
1034                                   rejected_pdu.itt, opcode);
1035                 /*
1036                  * We only send one TMF at a time so if the target could not
1037                  * handle it, then it should get fixed (RFC mandates that
1038                  * a target can handle one immediate TMF per conn).
1039                  *
1040                  * For nops-outs, we could have sent more than one if
1041                  * the target is sending us lots of nop-ins
1042                  */
1043                 if (opcode != ISCSI_OP_NOOP_OUT)
1044                         return 0;
1045
1046                  if (rejected_pdu.itt == cpu_to_be32(ISCSI_RESERVED_TAG))
1047                         /*
1048                          * nop-out in response to target's nop-out rejected.
1049                          * Just resend.
1050                          */
1051                         iscsi_send_nopout(conn,
1052                                           (struct iscsi_nopin*)&rejected_pdu);
1053                 else {
1054                         struct iscsi_task *task;
1055                         /*
1056                          * Our nop as ping got dropped. We know the target
1057                          * and transport are ok so just clean up
1058                          */
1059                         task = iscsi_itt_to_task(conn, rejected_pdu.itt);
1060                         if (!task) {
1061                                 iscsi_conn_printk(KERN_ERR, conn,
1062                                                  "Invalid pdu reject. Could "
1063                                                  "not lookup rejected task.\n");
1064                                 rc = ISCSI_ERR_BAD_ITT;
1065                         } else
1066                                 rc = iscsi_nop_out_rsp(task,
1067                                         (struct iscsi_nopin*)&rejected_pdu,
1068                                         NULL, 0);
1069                 }
1070                 break;
1071         default:
1072                 iscsi_conn_printk(KERN_ERR, conn,
1073                                   "pdu (op 0x%x itt 0x%x) rejected. Reason "
1074                                   "code 0x%x\n", rejected_pdu.itt,
1075                                   rejected_pdu.opcode, reject->reason);
1076                 break;
1077         }
1078         return rc;
1079 }
1080
1081 /**
1082  * iscsi_itt_to_task - look up task by itt
1083  * @conn: iscsi connection
1084  * @itt: itt
1085  *
1086  * This should be used for mgmt tasks like login and nops, or if
1087  * the LDD's itt space does not include the session age.
1088  *
1089  * The session lock must be held.
1090  */
1091 struct iscsi_task *iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt)
1092 {
1093         struct iscsi_session *session = conn->session;
1094         int i;
1095
1096         if (itt == RESERVED_ITT)
1097                 return NULL;
1098
1099         if (session->tt->parse_pdu_itt)
1100                 session->tt->parse_pdu_itt(conn, itt, &i, NULL);
1101         else
1102                 i = get_itt(itt);
1103         if (i >= session->cmds_max)
1104                 return NULL;
1105
1106         return session->cmds[i];
1107 }
1108 EXPORT_SYMBOL_GPL(iscsi_itt_to_task);
1109
1110 /**
1111  * __iscsi_complete_pdu - complete pdu
1112  * @conn: iscsi conn
1113  * @hdr: iscsi header
1114  * @data: data buffer
1115  * @datalen: len of data buffer
1116  *
1117  * Completes pdu processing by freeing any resources allocated at
1118  * queuecommand or send generic. session lock must be held and verify
1119  * itt must have been called.
1120  */
1121 int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1122                          char *data, int datalen)
1123 {
1124         struct iscsi_session *session = conn->session;
1125         int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0;
1126         struct iscsi_task *task;
1127         uint32_t itt;
1128
1129         conn->last_recv = jiffies;
1130         rc = iscsi_verify_itt(conn, hdr->itt);
1131         if (rc)
1132                 return rc;
1133
1134         if (hdr->itt != RESERVED_ITT)
1135                 itt = get_itt(hdr->itt);
1136         else
1137                 itt = ~0U;
1138
1139         ISCSI_DBG_SESSION(session, "[op 0x%x cid %d itt 0x%x len %d]\n",
1140                           opcode, conn->id, itt, datalen);
1141
1142         if (itt == ~0U) {
1143                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1144
1145                 switch(opcode) {
1146                 case ISCSI_OP_NOOP_IN:
1147                         if (datalen) {
1148                                 rc = ISCSI_ERR_PROTO;
1149                                 break;
1150                         }
1151
1152                         if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG))
1153                                 break;
1154
1155                         iscsi_send_nopout(conn, (struct iscsi_nopin*)hdr);
1156                         break;
1157                 case ISCSI_OP_REJECT:
1158                         rc = iscsi_handle_reject(conn, hdr, data, datalen);
1159                         break;
1160                 case ISCSI_OP_ASYNC_EVENT:
1161                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1162                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
1163                                 rc = ISCSI_ERR_CONN_FAILED;
1164                         break;
1165                 default:
1166                         rc = ISCSI_ERR_BAD_OPCODE;
1167                         break;
1168                 }
1169                 goto out;
1170         }
1171
1172         switch(opcode) {
1173         case ISCSI_OP_SCSI_CMD_RSP:
1174         case ISCSI_OP_SCSI_DATA_IN:
1175                 task = iscsi_itt_to_ctask(conn, hdr->itt);
1176                 if (!task)
1177                         return ISCSI_ERR_BAD_ITT;
1178                 task->last_xfer = jiffies;
1179                 break;
1180         case ISCSI_OP_R2T:
1181                 /*
1182                  * LLD handles R2Ts if they need to.
1183                  */
1184                 return 0;
1185         case ISCSI_OP_LOGOUT_RSP:
1186         case ISCSI_OP_LOGIN_RSP:
1187         case ISCSI_OP_TEXT_RSP:
1188         case ISCSI_OP_SCSI_TMFUNC_RSP:
1189         case ISCSI_OP_NOOP_IN:
1190                 task = iscsi_itt_to_task(conn, hdr->itt);
1191                 if (!task)
1192                         return ISCSI_ERR_BAD_ITT;
1193                 break;
1194         default:
1195                 return ISCSI_ERR_BAD_OPCODE;
1196         }
1197
1198         switch(opcode) {
1199         case ISCSI_OP_SCSI_CMD_RSP:
1200                 iscsi_scsi_cmd_rsp(conn, hdr, task, data, datalen);
1201                 break;
1202         case ISCSI_OP_SCSI_DATA_IN:
1203                 iscsi_data_in_rsp(conn, hdr, task);
1204                 break;
1205         case ISCSI_OP_LOGOUT_RSP:
1206                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1207                 if (datalen) {
1208                         rc = ISCSI_ERR_PROTO;
1209                         break;
1210                 }
1211                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1212                 goto recv_pdu;
1213         case ISCSI_OP_LOGIN_RSP:
1214         case ISCSI_OP_TEXT_RSP:
1215                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1216                 /*
1217                  * login related PDU's exp_statsn is handled in
1218                  * userspace
1219                  */
1220                 goto recv_pdu;
1221         case ISCSI_OP_SCSI_TMFUNC_RSP:
1222                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1223                 if (datalen) {
1224                         rc = ISCSI_ERR_PROTO;
1225                         break;
1226                 }
1227
1228                 iscsi_tmf_rsp(conn, hdr);
1229                 iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1230                 break;
1231         case ISCSI_OP_NOOP_IN:
1232                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1233                 if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) || datalen) {
1234                         rc = ISCSI_ERR_PROTO;
1235                         break;
1236                 }
1237                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1238
1239                 rc = iscsi_nop_out_rsp(task, (struct iscsi_nopin*)hdr,
1240                                        data, datalen);
1241                 break;
1242         default:
1243                 rc = ISCSI_ERR_BAD_OPCODE;
1244                 break;
1245         }
1246
1247 out:
1248         return rc;
1249 recv_pdu:
1250         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
1251                 rc = ISCSI_ERR_CONN_FAILED;
1252         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1253         return rc;
1254 }
1255 EXPORT_SYMBOL_GPL(__iscsi_complete_pdu);
1256
1257 int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1258                        char *data, int datalen)
1259 {
1260         int rc;
1261
1262         spin_lock(&conn->session->lock);
1263         rc = __iscsi_complete_pdu(conn, hdr, data, datalen);
1264         spin_unlock(&conn->session->lock);
1265         return rc;
1266 }
1267 EXPORT_SYMBOL_GPL(iscsi_complete_pdu);
1268
1269 int iscsi_verify_itt(struct iscsi_conn *conn, itt_t itt)
1270 {
1271         struct iscsi_session *session = conn->session;
1272         int age = 0, i = 0;
1273
1274         if (itt == RESERVED_ITT)
1275                 return 0;
1276
1277         if (session->tt->parse_pdu_itt)
1278                 session->tt->parse_pdu_itt(conn, itt, &i, &age);
1279         else {
1280                 i = get_itt(itt);
1281                 age = ((__force u32)itt >> ISCSI_AGE_SHIFT) & ISCSI_AGE_MASK;
1282         }
1283
1284         if (age != session->age) {
1285                 iscsi_conn_printk(KERN_ERR, conn,
1286                                   "received itt %x expected session age (%x)\n",
1287                                   (__force u32)itt, session->age);
1288                 return ISCSI_ERR_BAD_ITT;
1289         }
1290
1291         if (i >= session->cmds_max) {
1292                 iscsi_conn_printk(KERN_ERR, conn,
1293                                   "received invalid itt index %u (max cmds "
1294                                    "%u.\n", i, session->cmds_max);
1295                 return ISCSI_ERR_BAD_ITT;
1296         }
1297         return 0;
1298 }
1299 EXPORT_SYMBOL_GPL(iscsi_verify_itt);
1300
1301 /**
1302  * iscsi_itt_to_ctask - look up ctask by itt
1303  * @conn: iscsi connection
1304  * @itt: itt
1305  *
1306  * This should be used for cmd tasks.
1307  *
1308  * The session lock must be held.
1309  */
1310 struct iscsi_task *iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt)
1311 {
1312         struct iscsi_task *task;
1313
1314         if (iscsi_verify_itt(conn, itt))
1315                 return NULL;
1316
1317         task = iscsi_itt_to_task(conn, itt);
1318         if (!task || !task->sc)
1319                 return NULL;
1320
1321         if (task->sc->SCp.phase != conn->session->age) {
1322                 iscsi_session_printk(KERN_ERR, conn->session,
1323                                   "task's session age %d, expected %d\n",
1324                                   task->sc->SCp.phase, conn->session->age);
1325                 return NULL;
1326         }
1327
1328         return task;
1329 }
1330 EXPORT_SYMBOL_GPL(iscsi_itt_to_ctask);
1331
1332 void iscsi_session_failure(struct iscsi_session *session,
1333                            enum iscsi_err err)
1334 {
1335         struct iscsi_conn *conn;
1336         struct device *dev;
1337         unsigned long flags;
1338
1339         spin_lock_irqsave(&session->lock, flags);
1340         conn = session->leadconn;
1341         if (session->state == ISCSI_STATE_TERMINATE || !conn) {
1342                 spin_unlock_irqrestore(&session->lock, flags);
1343                 return;
1344         }
1345
1346         dev = get_device(&conn->cls_conn->dev);
1347         spin_unlock_irqrestore(&session->lock, flags);
1348         if (!dev)
1349                 return;
1350         /*
1351          * if the host is being removed bypass the connection
1352          * recovery initialization because we are going to kill
1353          * the session.
1354          */
1355         if (err == ISCSI_ERR_INVALID_HOST)
1356                 iscsi_conn_error_event(conn->cls_conn, err);
1357         else
1358                 iscsi_conn_failure(conn, err);
1359         put_device(dev);
1360 }
1361 EXPORT_SYMBOL_GPL(iscsi_session_failure);
1362
1363 void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err)
1364 {
1365         struct iscsi_session *session = conn->session;
1366         unsigned long flags;
1367
1368         spin_lock_irqsave(&session->lock, flags);
1369         if (session->state == ISCSI_STATE_FAILED) {
1370                 spin_unlock_irqrestore(&session->lock, flags);
1371                 return;
1372         }
1373
1374         if (conn->stop_stage == 0)
1375                 session->state = ISCSI_STATE_FAILED;
1376         spin_unlock_irqrestore(&session->lock, flags);
1377
1378         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1379         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1380         iscsi_conn_error_event(conn->cls_conn, err);
1381 }
1382 EXPORT_SYMBOL_GPL(iscsi_conn_failure);
1383
1384 static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn)
1385 {
1386         struct iscsi_session *session = conn->session;
1387
1388         /*
1389          * Check for iSCSI window and take care of CmdSN wrap-around
1390          */
1391         if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) {
1392                 ISCSI_DBG_SESSION(session, "iSCSI CmdSN closed. ExpCmdSn "
1393                                   "%u MaxCmdSN %u CmdSN %u/%u\n",
1394                                   session->exp_cmdsn, session->max_cmdsn,
1395                                   session->cmdsn, session->queued_cmdsn);
1396                 return -ENOSPC;
1397         }
1398         return 0;
1399 }
1400
1401 static int iscsi_xmit_task(struct iscsi_conn *conn)
1402 {
1403         struct iscsi_task *task = conn->task;
1404         int rc;
1405
1406         if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx))
1407                 return -ENODATA;
1408
1409         __iscsi_get_task(task);
1410         spin_unlock_bh(&conn->session->lock);
1411         rc = conn->session->tt->xmit_task(task);
1412         spin_lock_bh(&conn->session->lock);
1413         if (!rc) {
1414                 /* done with this task */
1415                 task->last_xfer = jiffies;
1416                 conn->task = NULL;
1417         }
1418         __iscsi_put_task(task);
1419         return rc;
1420 }
1421
1422 /**
1423  * iscsi_requeue_task - requeue task to run from session workqueue
1424  * @task: task to requeue
1425  *
1426  * LLDs that need to run a task from the session workqueue should call
1427  * this. The session lock must be held. This should only be called
1428  * by software drivers.
1429  */
1430 void iscsi_requeue_task(struct iscsi_task *task)
1431 {
1432         struct iscsi_conn *conn = task->conn;
1433
1434         /*
1435          * this may be on the requeue list already if the xmit_task callout
1436          * is handling the r2ts while we are adding new ones
1437          */
1438         if (list_empty(&task->running))
1439                 list_add_tail(&task->running, &conn->requeue);
1440         iscsi_conn_queue_work(conn);
1441 }
1442 EXPORT_SYMBOL_GPL(iscsi_requeue_task);
1443
1444 /**
1445  * iscsi_data_xmit - xmit any command into the scheduled connection
1446  * @conn: iscsi connection
1447  *
1448  * Notes:
1449  *      The function can return -EAGAIN in which case the caller must
1450  *      re-schedule it again later or recover. '0' return code means
1451  *      successful xmit.
1452  **/
1453 static int iscsi_data_xmit(struct iscsi_conn *conn)
1454 {
1455         struct iscsi_task *task;
1456         int rc = 0;
1457
1458         spin_lock_bh(&conn->session->lock);
1459         if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) {
1460                 ISCSI_DBG_SESSION(conn->session, "Tx suspended!\n");
1461                 spin_unlock_bh(&conn->session->lock);
1462                 return -ENODATA;
1463         }
1464
1465         if (conn->task) {
1466                 rc = iscsi_xmit_task(conn);
1467                 if (rc)
1468                         goto done;
1469         }
1470
1471         /*
1472          * process mgmt pdus like nops before commands since we should
1473          * only have one nop-out as a ping from us and targets should not
1474          * overflow us with nop-ins
1475          */
1476 check_mgmt:
1477         while (!list_empty(&conn->mgmtqueue)) {
1478                 conn->task = list_entry(conn->mgmtqueue.next,
1479                                          struct iscsi_task, running);
1480                 list_del_init(&conn->task->running);
1481                 if (iscsi_prep_mgmt_task(conn, conn->task)) {
1482                         __iscsi_put_task(conn->task);
1483                         conn->task = NULL;
1484                         continue;
1485                 }
1486                 rc = iscsi_xmit_task(conn);
1487                 if (rc)
1488                         goto done;
1489         }
1490
1491         /* process pending command queue */
1492         while (!list_empty(&conn->cmdqueue)) {
1493                 conn->task = list_entry(conn->cmdqueue.next, struct iscsi_task,
1494                                         running);
1495                 list_del_init(&conn->task->running);
1496                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT) {
1497                         fail_scsi_task(conn->task, DID_IMM_RETRY);
1498                         continue;
1499                 }
1500                 rc = iscsi_prep_scsi_cmd_pdu(conn->task);
1501                 if (rc) {
1502                         if (rc == -ENOMEM || rc == -EACCES) {
1503                                 list_add_tail(&conn->task->running,
1504                                               &conn->cmdqueue);
1505                                 conn->task = NULL;
1506                                 goto done;
1507                         } else
1508                                 fail_scsi_task(conn->task, DID_ABORT);
1509                         continue;
1510                 }
1511                 rc = iscsi_xmit_task(conn);
1512                 if (rc)
1513                         goto done;
1514                 /*
1515                  * we could continuously get new task requests so
1516                  * we need to check the mgmt queue for nops that need to
1517                  * be sent to aviod starvation
1518                  */
1519                 if (!list_empty(&conn->mgmtqueue))
1520                         goto check_mgmt;
1521         }
1522
1523         while (!list_empty(&conn->requeue)) {
1524                 /*
1525                  * we always do fastlogout - conn stop code will clean up.
1526                  */
1527                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
1528                         break;
1529
1530                 task = list_entry(conn->requeue.next, struct iscsi_task,
1531                                   running);
1532                 if (iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_DATA_OUT))
1533                         break;
1534
1535                 conn->task = task;
1536                 list_del_init(&conn->task->running);
1537                 conn->task->state = ISCSI_TASK_RUNNING;
1538                 rc = iscsi_xmit_task(conn);
1539                 if (rc)
1540                         goto done;
1541                 if (!list_empty(&conn->mgmtqueue))
1542                         goto check_mgmt;
1543         }
1544         spin_unlock_bh(&conn->session->lock);
1545         return -ENODATA;
1546
1547 done:
1548         spin_unlock_bh(&conn->session->lock);
1549         return rc;
1550 }
1551
1552 static void iscsi_xmitworker(struct work_struct *work)
1553 {
1554         struct iscsi_conn *conn =
1555                 container_of(work, struct iscsi_conn, xmitwork);
1556         int rc;
1557         /*
1558          * serialize Xmit worker on a per-connection basis.
1559          */
1560         do {
1561                 rc = iscsi_data_xmit(conn);
1562         } while (rc >= 0 || rc == -EAGAIN);
1563 }
1564
1565 static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn,
1566                                                   struct scsi_cmnd *sc)
1567 {
1568         struct iscsi_task *task;
1569
1570         if (!kfifo_out(&conn->session->cmdpool.queue,
1571                          (void *) &task, sizeof(void *)))
1572                 return NULL;
1573
1574         sc->SCp.phase = conn->session->age;
1575         sc->SCp.ptr = (char *) task;
1576
1577         atomic_set(&task->refcount, 1);
1578         task->state = ISCSI_TASK_PENDING;
1579         task->conn = conn;
1580         task->sc = sc;
1581         task->have_checked_conn = false;
1582         task->last_timeout = jiffies;
1583         task->last_xfer = jiffies;
1584         INIT_LIST_HEAD(&task->running);
1585         return task;
1586 }
1587
1588 enum {
1589         FAILURE_BAD_HOST = 1,
1590         FAILURE_SESSION_FAILED,
1591         FAILURE_SESSION_FREED,
1592         FAILURE_WINDOW_CLOSED,
1593         FAILURE_OOM,
1594         FAILURE_SESSION_TERMINATE,
1595         FAILURE_SESSION_IN_RECOVERY,
1596         FAILURE_SESSION_RECOVERY_TIMEOUT,
1597         FAILURE_SESSION_LOGGING_OUT,
1598         FAILURE_SESSION_NOT_READY,
1599 };
1600
1601 int iscsi_queuecommand(struct scsi_cmnd *sc, void (*done)(struct scsi_cmnd *))
1602 {
1603         struct iscsi_cls_session *cls_session;
1604         struct Scsi_Host *host;
1605         struct iscsi_host *ihost;
1606         int reason = 0;
1607         struct iscsi_session *session;
1608         struct iscsi_conn *conn;
1609         struct iscsi_task *task = NULL;
1610
1611         sc->scsi_done = done;
1612         sc->result = 0;
1613         sc->SCp.ptr = NULL;
1614
1615         host = sc->device->host;
1616         ihost = shost_priv(host);
1617         spin_unlock(host->host_lock);
1618
1619         cls_session = starget_to_session(scsi_target(sc->device));
1620         session = cls_session->dd_data;
1621         spin_lock(&session->lock);
1622
1623         reason = iscsi_session_chkready(cls_session);
1624         if (reason) {
1625                 sc->result = reason;
1626                 goto fault;
1627         }
1628
1629         if (session->state != ISCSI_STATE_LOGGED_IN) {
1630                 /*
1631                  * to handle the race between when we set the recovery state
1632                  * and block the session we requeue here (commands could
1633                  * be entering our queuecommand while a block is starting
1634                  * up because the block code is not locked)
1635                  */
1636                 switch (session->state) {
1637                 case ISCSI_STATE_FAILED:
1638                 case ISCSI_STATE_IN_RECOVERY:
1639                         reason = FAILURE_SESSION_IN_RECOVERY;
1640                         sc->result = DID_IMM_RETRY << 16;
1641                         break;
1642                 case ISCSI_STATE_LOGGING_OUT:
1643                         reason = FAILURE_SESSION_LOGGING_OUT;
1644                         sc->result = DID_IMM_RETRY << 16;
1645                         break;
1646                 case ISCSI_STATE_RECOVERY_FAILED:
1647                         reason = FAILURE_SESSION_RECOVERY_TIMEOUT;
1648                         sc->result = DID_TRANSPORT_FAILFAST << 16;
1649                         break;
1650                 case ISCSI_STATE_TERMINATE:
1651                         reason = FAILURE_SESSION_TERMINATE;
1652                         sc->result = DID_NO_CONNECT << 16;
1653                         break;
1654                 default:
1655                         reason = FAILURE_SESSION_FREED;
1656                         sc->result = DID_NO_CONNECT << 16;
1657                 }
1658                 goto fault;
1659         }
1660
1661         conn = session->leadconn;
1662         if (!conn) {
1663                 reason = FAILURE_SESSION_FREED;
1664                 sc->result = DID_NO_CONNECT << 16;
1665                 goto fault;
1666         }
1667
1668         if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) {
1669                 reason = FAILURE_SESSION_IN_RECOVERY;
1670                 sc->result = DID_REQUEUE;
1671                 goto fault;
1672         }
1673
1674         if (iscsi_check_cmdsn_window_closed(conn)) {
1675                 reason = FAILURE_WINDOW_CLOSED;
1676                 goto reject;
1677         }
1678
1679         task = iscsi_alloc_task(conn, sc);
1680         if (!task) {
1681                 reason = FAILURE_OOM;
1682                 goto reject;
1683         }
1684
1685         if (!ihost->workq) {
1686                 reason = iscsi_prep_scsi_cmd_pdu(task);
1687                 if (reason) {
1688                         if (reason == -ENOMEM ||  reason == -EACCES) {
1689                                 reason = FAILURE_OOM;
1690                                 goto prepd_reject;
1691                         } else {
1692                                 sc->result = DID_ABORT << 16;
1693                                 goto prepd_fault;
1694                         }
1695                 }
1696                 if (session->tt->xmit_task(task)) {
1697                         session->cmdsn--;
1698                         reason = FAILURE_SESSION_NOT_READY;
1699                         goto prepd_reject;
1700                 }
1701         } else {
1702                 list_add_tail(&task->running, &conn->cmdqueue);
1703                 iscsi_conn_queue_work(conn);
1704         }
1705
1706         session->queued_cmdsn++;
1707         spin_unlock(&session->lock);
1708         spin_lock(host->host_lock);
1709         return 0;
1710
1711 prepd_reject:
1712         sc->scsi_done = NULL;
1713         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1714 reject:
1715         spin_unlock(&session->lock);
1716         ISCSI_DBG_SESSION(session, "cmd 0x%x rejected (%d)\n",
1717                           sc->cmnd[0], reason);
1718         spin_lock(host->host_lock);
1719         return SCSI_MLQUEUE_TARGET_BUSY;
1720
1721 prepd_fault:
1722         sc->scsi_done = NULL;
1723         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1724 fault:
1725         spin_unlock(&session->lock);
1726         ISCSI_DBG_SESSION(session, "iscsi: cmd 0x%x is not queued (%d)\n",
1727                           sc->cmnd[0], reason);
1728         if (!scsi_bidi_cmnd(sc))
1729                 scsi_set_resid(sc, scsi_bufflen(sc));
1730         else {
1731                 scsi_out(sc)->resid = scsi_out(sc)->length;
1732                 scsi_in(sc)->resid = scsi_in(sc)->length;
1733         }
1734         done(sc);
1735         spin_lock(host->host_lock);
1736         return 0;
1737 }
1738 EXPORT_SYMBOL_GPL(iscsi_queuecommand);
1739
1740 int iscsi_change_queue_depth(struct scsi_device *sdev, int depth, int reason)
1741 {
1742         switch (reason) {
1743         case SCSI_QDEPTH_DEFAULT:
1744                 scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth);
1745                 break;
1746         case SCSI_QDEPTH_QFULL:
1747                 scsi_track_queue_full(sdev, depth);
1748                 break;
1749         case SCSI_QDEPTH_RAMP_UP:
1750                 scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth);
1751                 break;
1752         default:
1753                 return -EOPNOTSUPP;
1754         }
1755         return sdev->queue_depth;
1756 }
1757 EXPORT_SYMBOL_GPL(iscsi_change_queue_depth);
1758
1759 int iscsi_target_alloc(struct scsi_target *starget)
1760 {
1761         struct iscsi_cls_session *cls_session = starget_to_session(starget);
1762         struct iscsi_session *session = cls_session->dd_data;
1763
1764         starget->can_queue = session->scsi_cmds_max;
1765         return 0;
1766 }
1767 EXPORT_SYMBOL_GPL(iscsi_target_alloc);
1768
1769 static void iscsi_tmf_timedout(unsigned long data)
1770 {
1771         struct iscsi_conn *conn = (struct iscsi_conn *)data;
1772         struct iscsi_session *session = conn->session;
1773
1774         spin_lock(&session->lock);
1775         if (conn->tmf_state == TMF_QUEUED) {
1776                 conn->tmf_state = TMF_TIMEDOUT;
1777                 ISCSI_DBG_EH(session, "tmf timedout\n");
1778                 /* unblock eh_abort() */
1779                 wake_up(&conn->ehwait);
1780         }
1781         spin_unlock(&session->lock);
1782 }
1783
1784 static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn,
1785                                    struct iscsi_tm *hdr, int age,
1786                                    int timeout)
1787 {
1788         struct iscsi_session *session = conn->session;
1789         struct iscsi_task *task;
1790
1791         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr,
1792                                       NULL, 0);
1793         if (!task) {
1794                 spin_unlock_bh(&session->lock);
1795                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1796                 spin_lock_bh(&session->lock);
1797                 ISCSI_DBG_EH(session, "tmf exec failure\n");
1798                 return -EPERM;
1799         }
1800         conn->tmfcmd_pdus_cnt++;
1801         conn->tmf_timer.expires = timeout * HZ + jiffies;
1802         conn->tmf_timer.function = iscsi_tmf_timedout;
1803         conn->tmf_timer.data = (unsigned long)conn;
1804         add_timer(&conn->tmf_timer);
1805         ISCSI_DBG_EH(session, "tmf set timeout\n");
1806
1807         spin_unlock_bh(&session->lock);
1808         mutex_unlock(&session->eh_mutex);
1809
1810         /*
1811          * block eh thread until:
1812          *
1813          * 1) tmf response
1814          * 2) tmf timeout
1815          * 3) session is terminated or restarted or userspace has
1816          * given up on recovery
1817          */
1818         wait_event_interruptible(conn->ehwait, age != session->age ||
1819                                  session->state != ISCSI_STATE_LOGGED_IN ||
1820                                  conn->tmf_state != TMF_QUEUED);
1821         if (signal_pending(current))
1822                 flush_signals(current);
1823         del_timer_sync(&conn->tmf_timer);
1824
1825         mutex_lock(&session->eh_mutex);
1826         spin_lock_bh(&session->lock);
1827         /* if the session drops it will clean up the task */
1828         if (age != session->age ||
1829             session->state != ISCSI_STATE_LOGGED_IN)
1830                 return -ENOTCONN;
1831         return 0;
1832 }
1833
1834 /*
1835  * Fail commands. session lock held and recv side suspended and xmit
1836  * thread flushed
1837  */
1838 static void fail_scsi_tasks(struct iscsi_conn *conn, unsigned lun,
1839                             int error)
1840 {
1841         struct iscsi_task *task;
1842         int i;
1843
1844         for (i = 0; i < conn->session->cmds_max; i++) {
1845                 task = conn->session->cmds[i];
1846                 if (!task->sc || task->state == ISCSI_TASK_FREE)
1847                         continue;
1848
1849                 if (lun != -1 && lun != task->sc->device->lun)
1850                         continue;
1851
1852                 ISCSI_DBG_SESSION(conn->session,
1853                                   "failing sc %p itt 0x%x state %d\n",
1854                                   task->sc, task->itt, task->state);
1855                 fail_scsi_task(task, error);
1856         }
1857 }
1858
1859 /**
1860  * iscsi_suspend_queue - suspend iscsi_queuecommand
1861  * @conn: iscsi conn to stop queueing IO on
1862  *
1863  * This grabs the session lock to make sure no one is in
1864  * xmit_task/queuecommand, and then sets suspend to prevent
1865  * new commands from being queued. This only needs to be called
1866  * by offload drivers that need to sync a path like ep disconnect
1867  * with the iscsi_queuecommand/xmit_task. To start IO again libiscsi
1868  * will call iscsi_start_tx and iscsi_unblock_session when in FFP.
1869  */
1870 void iscsi_suspend_queue(struct iscsi_conn *conn)
1871 {
1872         spin_lock_bh(&conn->session->lock);
1873         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1874         spin_unlock_bh(&conn->session->lock);
1875 }
1876 EXPORT_SYMBOL_GPL(iscsi_suspend_queue);
1877
1878 /**
1879  * iscsi_suspend_tx - suspend iscsi_data_xmit
1880  * @conn: iscsi conn tp stop processing IO on.
1881  *
1882  * This function sets the suspend bit to prevent iscsi_data_xmit
1883  * from sending new IO, and if work is queued on the xmit thread
1884  * it will wait for it to be completed.
1885  */
1886 void iscsi_suspend_tx(struct iscsi_conn *conn)
1887 {
1888         struct Scsi_Host *shost = conn->session->host;
1889         struct iscsi_host *ihost = shost_priv(shost);
1890
1891         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1892         if (ihost->workq)
1893                 flush_workqueue(ihost->workq);
1894 }
1895 EXPORT_SYMBOL_GPL(iscsi_suspend_tx);
1896
1897 static void iscsi_start_tx(struct iscsi_conn *conn)
1898 {
1899         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1900         iscsi_conn_queue_work(conn);
1901 }
1902
1903 /*
1904  * We want to make sure a ping is in flight. It has timed out.
1905  * And we are not busy processing a pdu that is making
1906  * progress but got started before the ping and is taking a while
1907  * to complete so the ping is just stuck behind it in a queue.
1908  */
1909 static int iscsi_has_ping_timed_out(struct iscsi_conn *conn)
1910 {
1911         if (conn->ping_task &&
1912             time_before_eq(conn->last_recv + (conn->recv_timeout * HZ) +
1913                            (conn->ping_timeout * HZ), jiffies))
1914                 return 1;
1915         else
1916                 return 0;
1917 }
1918
1919 static enum blk_eh_timer_return iscsi_eh_cmd_timed_out(struct scsi_cmnd *sc)
1920 {
1921         enum blk_eh_timer_return rc = BLK_EH_NOT_HANDLED;
1922         struct iscsi_task *task = NULL, *running_task;
1923         struct iscsi_cls_session *cls_session;
1924         struct iscsi_session *session;
1925         struct iscsi_conn *conn;
1926         int i;
1927
1928         cls_session = starget_to_session(scsi_target(sc->device));
1929         session = cls_session->dd_data;
1930
1931         ISCSI_DBG_EH(session, "scsi cmd %p timedout\n", sc);
1932
1933         spin_lock(&session->lock);
1934         if (session->state != ISCSI_STATE_LOGGED_IN) {
1935                 /*
1936                  * We are probably in the middle of iscsi recovery so let
1937                  * that complete and handle the error.
1938                  */
1939                 rc = BLK_EH_RESET_TIMER;
1940                 goto done;
1941         }
1942
1943         conn = session->leadconn;
1944         if (!conn) {
1945                 /* In the middle of shuting down */
1946                 rc = BLK_EH_RESET_TIMER;
1947                 goto done;
1948         }
1949
1950         task = (struct iscsi_task *)sc->SCp.ptr;
1951         if (!task) {
1952                 /*
1953                  * Raced with completion. Just reset timer, and let it
1954                  * complete normally
1955                  */
1956                 rc = BLK_EH_RESET_TIMER;
1957                 goto done;
1958         }
1959
1960         /*
1961          * If we have sent (at least queued to the network layer) a pdu or
1962          * recvd one for the task since the last timeout ask for
1963          * more time. If on the next timeout we have not made progress
1964          * we can check if it is the task or connection when we send the
1965          * nop as a ping.
1966          */
1967         if (time_after(task->last_xfer, task->last_timeout)) {
1968                 ISCSI_DBG_EH(session, "Command making progress. Asking "
1969                              "scsi-ml for more time to complete. "
1970                              "Last data xfer at %lu. Last timeout was at "
1971                              "%lu\n.", task->last_xfer, task->last_timeout);
1972                 task->have_checked_conn = false;
1973                 rc = BLK_EH_RESET_TIMER;
1974                 goto done;
1975         }
1976
1977         if (!conn->recv_timeout && !conn->ping_timeout)
1978                 goto done;
1979         /*
1980          * if the ping timedout then we are in the middle of cleaning up
1981          * and can let the iscsi eh handle it
1982          */
1983         if (iscsi_has_ping_timed_out(conn)) {
1984                 rc = BLK_EH_RESET_TIMER;
1985                 goto done;
1986         }
1987
1988         for (i = 0; i < conn->session->cmds_max; i++) {
1989                 running_task = conn->session->cmds[i];
1990                 if (!running_task->sc || running_task == task ||
1991                      running_task->state != ISCSI_TASK_RUNNING)
1992                         continue;
1993
1994                 /*
1995                  * Only check if cmds started before this one have made
1996                  * progress, or this could never fail
1997                  */
1998                 if (time_after(running_task->sc->jiffies_at_alloc,
1999                                task->sc->jiffies_at_alloc))
2000                         continue;
2001
2002                 if (time_after(running_task->last_xfer, task->last_timeout)) {
2003                         /*
2004                          * This task has not made progress, but a task
2005                          * started before us has transferred data since
2006                          * we started/last-checked. We could be queueing
2007                          * too many tasks or the LU is bad.
2008                          *
2009                          * If the device is bad the cmds ahead of us on
2010                          * other devs will complete, and this loop will
2011                          * eventually fail starting the scsi eh.
2012                          */
2013                         ISCSI_DBG_EH(session, "Command has not made progress "
2014                                      "but commands ahead of it have. "
2015                                      "Asking scsi-ml for more time to "
2016                                      "complete. Our last xfer vs running task "
2017                                      "last xfer %lu/%lu. Last check %lu.\n",
2018                                      task->last_xfer, running_task->last_xfer,
2019                                      task->last_timeout);
2020                         rc = BLK_EH_RESET_TIMER;
2021                         goto done;
2022                 }
2023         }
2024
2025         /* Assumes nop timeout is shorter than scsi cmd timeout */
2026         if (task->have_checked_conn)
2027                 goto done;
2028
2029         /*
2030          * Checking the transport already or nop from a cmd timeout still
2031          * running
2032          */
2033         if (conn->ping_task) {
2034                 task->have_checked_conn = true;
2035                 rc = BLK_EH_RESET_TIMER;
2036                 goto done;
2037         }
2038
2039         /* Make sure there is a transport check done */
2040         iscsi_send_nopout(conn, NULL);
2041         task->have_checked_conn = true;
2042         rc = BLK_EH_RESET_TIMER;
2043
2044 done:
2045         if (task)
2046                 task->last_timeout = jiffies;
2047         spin_unlock(&session->lock);
2048         ISCSI_DBG_EH(session, "return %s\n", rc == BLK_EH_RESET_TIMER ?
2049                      "timer reset" : "nh");
2050         return rc;
2051 }
2052
2053 static void iscsi_check_transport_timeouts(unsigned long data)
2054 {
2055         struct iscsi_conn *conn = (struct iscsi_conn *)data;
2056         struct iscsi_session *session = conn->session;
2057         unsigned long recv_timeout, next_timeout = 0, last_recv;
2058
2059         spin_lock(&session->lock);
2060         if (session->state != ISCSI_STATE_LOGGED_IN)
2061                 goto done;
2062
2063         recv_timeout = conn->recv_timeout;
2064         if (!recv_timeout)
2065                 goto done;
2066
2067         recv_timeout *= HZ;
2068         last_recv = conn->last_recv;
2069
2070         if (iscsi_has_ping_timed_out(conn)) {
2071                 iscsi_conn_printk(KERN_ERR, conn, "ping timeout of %d secs "
2072                                   "expired, recv timeout %d, last rx %lu, "
2073                                   "last ping %lu, now %lu\n",
2074                                   conn->ping_timeout, conn->recv_timeout,
2075                                   last_recv, conn->last_ping, jiffies);
2076                 spin_unlock(&session->lock);
2077                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
2078                 return;
2079         }
2080
2081         if (time_before_eq(last_recv + recv_timeout, jiffies)) {
2082                 /* send a ping to try to provoke some traffic */
2083                 ISCSI_DBG_CONN(conn, "Sending nopout as ping\n");
2084                 iscsi_send_nopout(conn, NULL);
2085                 next_timeout = conn->last_ping + (conn->ping_timeout * HZ);
2086         } else
2087                 next_timeout = last_recv + recv_timeout;
2088
2089         ISCSI_DBG_CONN(conn, "Setting next tmo %lu\n", next_timeout);
2090         mod_timer(&conn->transport_timer, next_timeout);
2091 done:
2092         spin_unlock(&session->lock);
2093 }
2094
2095 static void iscsi_prep_abort_task_pdu(struct iscsi_task *task,
2096                                       struct iscsi_tm *hdr)
2097 {
2098         memset(hdr, 0, sizeof(*hdr));
2099         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2100         hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK;
2101         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2102         memcpy(hdr->lun, task->lun, sizeof(hdr->lun));
2103         hdr->rtt = task->hdr_itt;
2104         hdr->refcmdsn = task->cmdsn;
2105 }
2106
2107 int iscsi_eh_abort(struct scsi_cmnd *sc)
2108 {
2109         struct iscsi_cls_session *cls_session;
2110         struct iscsi_session *session;
2111         struct iscsi_conn *conn;
2112         struct iscsi_task *task;
2113         struct iscsi_tm *hdr;
2114         int rc, age;
2115
2116         cls_session = starget_to_session(scsi_target(sc->device));
2117         session = cls_session->dd_data;
2118
2119         ISCSI_DBG_EH(session, "aborting sc %p\n", sc);
2120
2121         mutex_lock(&session->eh_mutex);
2122         spin_lock_bh(&session->lock);
2123         /*
2124          * if session was ISCSI_STATE_IN_RECOVERY then we may not have
2125          * got the command.
2126          */
2127         if (!sc->SCp.ptr) {
2128                 ISCSI_DBG_EH(session, "sc never reached iscsi layer or "
2129                                       "it completed.\n");
2130                 spin_unlock_bh(&session->lock);
2131                 mutex_unlock(&session->eh_mutex);
2132                 return SUCCESS;
2133         }
2134
2135         /*
2136          * If we are not logged in or we have started a new session
2137          * then let the host reset code handle this
2138          */
2139         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN ||
2140             sc->SCp.phase != session->age) {
2141                 spin_unlock_bh(&session->lock);
2142                 mutex_unlock(&session->eh_mutex);
2143                 ISCSI_DBG_EH(session, "failing abort due to dropped "
2144                                   "session.\n");
2145                 return FAILED;
2146         }
2147
2148         conn = session->leadconn;
2149         conn->eh_abort_cnt++;
2150         age = session->age;
2151
2152         task = (struct iscsi_task *)sc->SCp.ptr;
2153         ISCSI_DBG_EH(session, "aborting [sc %p itt 0x%x]\n",
2154                      sc, task->itt);
2155
2156         /* task completed before time out */
2157         if (!task->sc) {
2158                 ISCSI_DBG_EH(session, "sc completed while abort in progress\n");
2159                 goto success;
2160         }
2161
2162         if (task->state == ISCSI_TASK_PENDING) {
2163                 fail_scsi_task(task, DID_ABORT);
2164                 goto success;
2165         }
2166
2167         /* only have one tmf outstanding at a time */
2168         if (conn->tmf_state != TMF_INITIAL)
2169                 goto failed;
2170         conn->tmf_state = TMF_QUEUED;
2171
2172         hdr = &conn->tmhdr;
2173         iscsi_prep_abort_task_pdu(task, hdr);
2174
2175         if (iscsi_exec_task_mgmt_fn(conn, hdr, age, session->abort_timeout)) {
2176                 rc = FAILED;
2177                 goto failed;
2178         }
2179
2180         switch (conn->tmf_state) {
2181         case TMF_SUCCESS:
2182                 spin_unlock_bh(&session->lock);
2183                 /*
2184                  * stop tx side incase the target had sent a abort rsp but
2185                  * the initiator was still writing out data.
2186                  */
2187                 iscsi_suspend_tx(conn);
2188                 /*
2189                  * we do not stop the recv side because targets have been
2190                  * good and have never sent us a successful tmf response
2191                  * then sent more data for the cmd.
2192                  */
2193                 spin_lock_bh(&session->lock);
2194                 fail_scsi_task(task, DID_ABORT);
2195                 conn->tmf_state = TMF_INITIAL;
2196                 memset(hdr, 0, sizeof(*hdr));
2197                 spin_unlock_bh(&session->lock);
2198                 iscsi_start_tx(conn);
2199                 goto success_unlocked;
2200         case TMF_TIMEDOUT:
2201                 spin_unlock_bh(&session->lock);
2202                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
2203                 goto failed_unlocked;
2204         case TMF_NOT_FOUND:
2205                 if (!sc->SCp.ptr) {
2206                         conn->tmf_state = TMF_INITIAL;
2207                         memset(hdr, 0, sizeof(*hdr));
2208                         /* task completed before tmf abort response */
2209                         ISCSI_DBG_EH(session, "sc completed while abort in "
2210                                               "progress\n");
2211                         goto success;
2212                 }
2213                 /* fall through */
2214         default:
2215                 conn->tmf_state = TMF_INITIAL;
2216                 goto failed;
2217         }
2218
2219 success:
2220         spin_unlock_bh(&session->lock);
2221 success_unlocked:
2222         ISCSI_DBG_EH(session, "abort success [sc %p itt 0x%x]\n",
2223                      sc, task->itt);
2224         mutex_unlock(&session->eh_mutex);
2225         return SUCCESS;
2226
2227 failed:
2228         spin_unlock_bh(&session->lock);
2229 failed_unlocked:
2230         ISCSI_DBG_EH(session, "abort failed [sc %p itt 0x%x]\n", sc,
2231                      task ? task->itt : 0);
2232         mutex_unlock(&session->eh_mutex);
2233         return FAILED;
2234 }
2235 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
2236
2237 static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
2238 {
2239         memset(hdr, 0, sizeof(*hdr));
2240         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2241         hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK;
2242         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2243         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
2244         hdr->rtt = RESERVED_ITT;
2245 }
2246
2247 int iscsi_eh_device_reset(struct scsi_cmnd *sc)
2248 {
2249         struct iscsi_cls_session *cls_session;
2250         struct iscsi_session *session;
2251         struct iscsi_conn *conn;
2252         struct iscsi_tm *hdr;
2253         int rc = FAILED;
2254
2255         cls_session = starget_to_session(scsi_target(sc->device));
2256         session = cls_session->dd_data;
2257
2258         ISCSI_DBG_EH(session, "LU Reset [sc %p lun %u]\n", sc, sc->device->lun);
2259
2260         mutex_lock(&session->eh_mutex);
2261         spin_lock_bh(&session->lock);
2262         /*
2263          * Just check if we are not logged in. We cannot check for
2264          * the phase because the reset could come from a ioctl.
2265          */
2266         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
2267                 goto unlock;
2268         conn = session->leadconn;
2269
2270         /* only have one tmf outstanding at a time */
2271         if (conn->tmf_state != TMF_INITIAL)
2272                 goto unlock;
2273         conn->tmf_state = TMF_QUEUED;
2274
2275         hdr = &conn->tmhdr;
2276         iscsi_prep_lun_reset_pdu(sc, hdr);
2277
2278         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
2279                                     session->lu_reset_timeout)) {
2280                 rc = FAILED;
2281                 goto unlock;
2282         }
2283
2284         switch (conn->tmf_state) {
2285         case TMF_SUCCESS:
2286                 break;
2287         case TMF_TIMEDOUT:
2288                 spin_unlock_bh(&session->lock);
2289                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
2290                 goto done;
2291         default:
2292                 conn->tmf_state = TMF_INITIAL;
2293                 goto unlock;
2294         }
2295
2296         rc = SUCCESS;
2297         spin_unlock_bh(&session->lock);
2298
2299         iscsi_suspend_tx(conn);
2300
2301         spin_lock_bh(&session->lock);
2302         memset(hdr, 0, sizeof(*hdr));
2303         fail_scsi_tasks(conn, sc->device->lun, DID_ERROR);
2304         conn->tmf_state = TMF_INITIAL;
2305         spin_unlock_bh(&session->lock);
2306
2307         iscsi_start_tx(conn);
2308         goto done;
2309
2310 unlock:
2311         spin_unlock_bh(&session->lock);
2312 done:
2313         ISCSI_DBG_EH(session, "dev reset result = %s\n",
2314                      rc == SUCCESS ? "SUCCESS" : "FAILED");
2315         mutex_unlock(&session->eh_mutex);
2316         return rc;
2317 }
2318 EXPORT_SYMBOL_GPL(iscsi_eh_device_reset);
2319
2320 void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session)
2321 {
2322         struct iscsi_session *session = cls_session->dd_data;
2323
2324         spin_lock_bh(&session->lock);
2325         if (session->state != ISCSI_STATE_LOGGED_IN) {
2326                 session->state = ISCSI_STATE_RECOVERY_FAILED;
2327                 if (session->leadconn)
2328                         wake_up(&session->leadconn->ehwait);
2329         }
2330         spin_unlock_bh(&session->lock);
2331 }
2332 EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout);
2333
2334 /**
2335  * iscsi_eh_session_reset - drop session and attempt relogin
2336  * @sc: scsi command
2337  *
2338  * This function will wait for a relogin, session termination from
2339  * userspace, or a recovery/replacement timeout.
2340  */
2341 static int iscsi_eh_session_reset(struct scsi_cmnd *sc)
2342 {
2343         struct iscsi_cls_session *cls_session;
2344         struct iscsi_session *session;
2345         struct iscsi_conn *conn;
2346
2347         cls_session = starget_to_session(scsi_target(sc->device));
2348         session = cls_session->dd_data;
2349         conn = session->leadconn;
2350
2351         mutex_lock(&session->eh_mutex);
2352         spin_lock_bh(&session->lock);
2353         if (session->state == ISCSI_STATE_TERMINATE) {
2354 failed:
2355                 ISCSI_DBG_EH(session,
2356                              "failing session reset: Could not log back into "
2357                              "%s, %s [age %d]\n", session->targetname,
2358                              conn->persistent_address, session->age);
2359                 spin_unlock_bh(&session->lock);
2360                 mutex_unlock(&session->eh_mutex);
2361                 return FAILED;
2362         }
2363
2364         spin_unlock_bh(&session->lock);
2365         mutex_unlock(&session->eh_mutex);
2366         /*
2367          * we drop the lock here but the leadconn cannot be destoyed while
2368          * we are in the scsi eh
2369          */
2370         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
2371
2372         ISCSI_DBG_EH(session, "wait for relogin\n");
2373         wait_event_interruptible(conn->ehwait,
2374                                  session->state == ISCSI_STATE_TERMINATE ||
2375                                  session->state == ISCSI_STATE_LOGGED_IN ||
2376                                  session->state == ISCSI_STATE_RECOVERY_FAILED);
2377         if (signal_pending(current))
2378                 flush_signals(current);
2379
2380         mutex_lock(&session->eh_mutex);
2381         spin_lock_bh(&session->lock);
2382         if (session->state == ISCSI_STATE_LOGGED_IN) {
2383                 ISCSI_DBG_EH(session,
2384                              "session reset succeeded for %s,%s\n",
2385                              session->targetname, conn->persistent_address);
2386         } else
2387                 goto failed;
2388         spin_unlock_bh(&session->lock);
2389         mutex_unlock(&session->eh_mutex);
2390         return SUCCESS;
2391 }
2392
2393 static void iscsi_prep_tgt_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
2394 {
2395         memset(hdr, 0, sizeof(*hdr));
2396         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2397         hdr->flags = ISCSI_TM_FUNC_TARGET_WARM_RESET & ISCSI_FLAG_TM_FUNC_MASK;
2398         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2399         hdr->rtt = RESERVED_ITT;
2400 }
2401
2402 /**
2403  * iscsi_eh_target_reset - reset target
2404  * @sc: scsi command
2405  *
2406  * This will attempt to send a warm target reset. If that fails
2407  * then we will drop the session and attempt ERL0 recovery.
2408  */
2409 int iscsi_eh_target_reset(struct scsi_cmnd *sc)
2410 {
2411         struct iscsi_cls_session *cls_session;
2412         struct iscsi_session *session;
2413         struct iscsi_conn *conn;
2414         struct iscsi_tm *hdr;
2415         int rc = FAILED;
2416
2417         cls_session = starget_to_session(scsi_target(sc->device));
2418         session = cls_session->dd_data;
2419
2420         ISCSI_DBG_EH(session, "tgt Reset [sc %p tgt %s]\n", sc,
2421                      session->targetname);
2422
2423         mutex_lock(&session->eh_mutex);
2424         spin_lock_bh(&session->lock);
2425         /*
2426          * Just check if we are not logged in. We cannot check for
2427          * the phase because the reset could come from a ioctl.
2428          */
2429         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
2430                 goto unlock;
2431         conn = session->leadconn;
2432
2433         /* only have one tmf outstanding at a time */
2434         if (conn->tmf_state != TMF_INITIAL)
2435                 goto unlock;
2436         conn->tmf_state = TMF_QUEUED;
2437
2438         hdr = &conn->tmhdr;
2439         iscsi_prep_tgt_reset_pdu(sc, hdr);
2440
2441         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
2442                                     session->tgt_reset_timeout)) {
2443                 rc = FAILED;
2444                 goto unlock;
2445         }
2446
2447         switch (conn->tmf_state) {
2448         case TMF_SUCCESS:
2449                 break;
2450         case TMF_TIMEDOUT:
2451                 spin_unlock_bh(&session->lock);
2452                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
2453                 goto done;
2454         default:
2455                 conn->tmf_state = TMF_INITIAL;
2456                 goto unlock;
2457         }
2458
2459         rc = SUCCESS;
2460         spin_unlock_bh(&session->lock);
2461
2462         iscsi_suspend_tx(conn);
2463
2464         spin_lock_bh(&session->lock);
2465         memset(hdr, 0, sizeof(*hdr));
2466         fail_scsi_tasks(conn, -1, DID_ERROR);
2467         conn->tmf_state = TMF_INITIAL;
2468         spin_unlock_bh(&session->lock);
2469
2470         iscsi_start_tx(conn);
2471         goto done;
2472
2473 unlock:
2474         spin_unlock_bh(&session->lock);
2475 done:
2476         ISCSI_DBG_EH(session, "tgt %s reset result = %s\n", session->targetname,
2477                      rc == SUCCESS ? "SUCCESS" : "FAILED");
2478         mutex_unlock(&session->eh_mutex);
2479
2480         if (rc == FAILED)
2481                 rc = iscsi_eh_session_reset(sc);
2482         return rc;
2483 }
2484 EXPORT_SYMBOL_GPL(iscsi_eh_target_reset);
2485
2486 /*
2487  * Pre-allocate a pool of @max items of @item_size. By default, the pool
2488  * should be accessed via kfifo_{get,put} on q->queue.
2489  * Optionally, the caller can obtain the array of object pointers
2490  * by passing in a non-NULL @items pointer
2491  */
2492 int
2493 iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size)
2494 {
2495         int i, num_arrays = 1;
2496
2497         memset(q, 0, sizeof(*q));
2498
2499         q->max = max;
2500
2501         /* If the user passed an items pointer, he wants a copy of
2502          * the array. */
2503         if (items)
2504                 num_arrays++;
2505         q->pool = kzalloc(num_arrays * max * sizeof(void*), GFP_KERNEL);
2506         if (q->pool == NULL)
2507                 return -ENOMEM;
2508
2509         kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*));
2510
2511         for (i = 0; i < max; i++) {
2512                 q->pool[i] = kzalloc(item_size, GFP_KERNEL);
2513                 if (q->pool[i] == NULL) {
2514                         q->max = i;
2515                         goto enomem;
2516                 }
2517                 kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*));
2518         }
2519
2520         if (items) {
2521                 *items = q->pool + max;
2522                 memcpy(*items, q->pool, max * sizeof(void *));
2523         }
2524
2525         return 0;
2526
2527 enomem:
2528         iscsi_pool_free(q);
2529         return -ENOMEM;
2530 }
2531 EXPORT_SYMBOL_GPL(iscsi_pool_init);
2532
2533 void iscsi_pool_free(struct iscsi_pool *q)
2534 {
2535         int i;
2536
2537         for (i = 0; i < q->max; i++)
2538                 kfree(q->pool[i]);
2539         kfree(q->pool);
2540 }
2541 EXPORT_SYMBOL_GPL(iscsi_pool_free);
2542
2543 /**
2544  * iscsi_host_add - add host to system
2545  * @shost: scsi host
2546  * @pdev: parent device
2547  *
2548  * This should be called by partial offload and software iscsi drivers
2549  * to add a host to the system.
2550  */
2551 int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev)
2552 {
2553         if (!shost->can_queue)
2554                 shost->can_queue = ISCSI_DEF_XMIT_CMDS_MAX;
2555
2556         if (!shost->cmd_per_lun)
2557                 shost->cmd_per_lun = ISCSI_DEF_CMD_PER_LUN;
2558
2559         if (!shost->transportt->eh_timed_out)
2560                 shost->transportt->eh_timed_out = iscsi_eh_cmd_timed_out;
2561         return scsi_add_host(shost, pdev);
2562 }
2563 EXPORT_SYMBOL_GPL(iscsi_host_add);
2564
2565 /**
2566  * iscsi_host_alloc - allocate a host and driver data
2567  * @sht: scsi host template
2568  * @dd_data_size: driver host data size
2569  * @xmit_can_sleep: bool indicating if LLD will queue IO from a work queue
2570  *
2571  * This should be called by partial offload and software iscsi drivers.
2572  * To access the driver specific memory use the iscsi_host_priv() macro.
2573  */
2574 struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht,
2575                                    int dd_data_size, bool xmit_can_sleep)
2576 {
2577         struct Scsi_Host *shost;
2578         struct iscsi_host *ihost;
2579
2580         shost = scsi_host_alloc(sht, sizeof(struct iscsi_host) + dd_data_size);
2581         if (!shost)
2582                 return NULL;
2583         ihost = shost_priv(shost);
2584
2585         if (xmit_can_sleep) {
2586                 snprintf(ihost->workq_name, sizeof(ihost->workq_name),
2587                         "iscsi_q_%d", shost->host_no);
2588                 ihost->workq = create_singlethread_workqueue(ihost->workq_name);
2589                 if (!ihost->workq)
2590                         goto free_host;
2591         }
2592
2593         spin_lock_init(&ihost->lock);
2594         ihost->state = ISCSI_HOST_SETUP;
2595         ihost->num_sessions = 0;
2596         init_waitqueue_head(&ihost->session_removal_wq);
2597         return shost;
2598
2599 free_host:
2600         scsi_host_put(shost);
2601         return NULL;
2602 }
2603 EXPORT_SYMBOL_GPL(iscsi_host_alloc);
2604
2605 static void iscsi_notify_host_removed(struct iscsi_cls_session *cls_session)
2606 {
2607         iscsi_session_failure(cls_session->dd_data, ISCSI_ERR_INVALID_HOST);
2608 }
2609
2610 /**
2611  * iscsi_host_remove - remove host and sessions
2612  * @shost: scsi host
2613  *
2614  * If there are any sessions left, this will initiate the removal and wait
2615  * for the completion.
2616  */
2617 void iscsi_host_remove(struct Scsi_Host *shost)
2618 {
2619         struct iscsi_host *ihost = shost_priv(shost);
2620         unsigned long flags;
2621
2622         spin_lock_irqsave(&ihost->lock, flags);
2623         ihost->state = ISCSI_HOST_REMOVED;
2624         spin_unlock_irqrestore(&ihost->lock, flags);
2625
2626         iscsi_host_for_each_session(shost, iscsi_notify_host_removed);
2627         wait_event_interruptible(ihost->session_removal_wq,
2628                                  ihost->num_sessions == 0);
2629         if (signal_pending(current))
2630                 flush_signals(current);
2631
2632         scsi_remove_host(shost);
2633         if (ihost->workq)
2634                 destroy_workqueue(ihost->workq);
2635 }
2636 EXPORT_SYMBOL_GPL(iscsi_host_remove);
2637
2638 void iscsi_host_free(struct Scsi_Host *shost)
2639 {
2640         struct iscsi_host *ihost = shost_priv(shost);
2641
2642         kfree(ihost->netdev);
2643         kfree(ihost->hwaddress);
2644         kfree(ihost->initiatorname);
2645         scsi_host_put(shost);
2646 }
2647 EXPORT_SYMBOL_GPL(iscsi_host_free);
2648
2649 static void iscsi_host_dec_session_cnt(struct Scsi_Host *shost)
2650 {
2651         struct iscsi_host *ihost = shost_priv(shost);
2652         unsigned long flags;
2653
2654         shost = scsi_host_get(shost);
2655         if (!shost) {
2656                 printk(KERN_ERR "Invalid state. Cannot notify host removal "
2657                       "of session teardown event because host already "
2658                       "removed.\n");
2659                 return;
2660         }
2661
2662         spin_lock_irqsave(&ihost->lock, flags);
2663         ihost->num_sessions--;
2664         if (ihost->num_sessions == 0)
2665                 wake_up(&ihost->session_removal_wq);
2666         spin_unlock_irqrestore(&ihost->lock, flags);
2667         scsi_host_put(shost);
2668 }
2669
2670 /**
2671  * iscsi_session_setup - create iscsi cls session and host and session
2672  * @iscsit: iscsi transport template
2673  * @shost: scsi host
2674  * @cmds_max: session can queue
2675  * @cmd_task_size: LLD task private data size
2676  * @initial_cmdsn: initial CmdSN
2677  *
2678  * This can be used by software iscsi_transports that allocate
2679  * a session per scsi host.
2680  *
2681  * Callers should set cmds_max to the largest total numer (mgmt + scsi) of
2682  * tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks
2683  * for nop handling and login/logout requests.
2684  */
2685 struct iscsi_cls_session *
2686 iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost,
2687                     uint16_t cmds_max, int dd_size, int cmd_task_size,
2688                     uint32_t initial_cmdsn, unsigned int id)
2689 {
2690         struct iscsi_host *ihost = shost_priv(shost);
2691         struct iscsi_session *session;
2692         struct iscsi_cls_session *cls_session;
2693         int cmd_i, scsi_cmds, total_cmds = cmds_max;
2694         unsigned long flags;
2695
2696         spin_lock_irqsave(&ihost->lock, flags);
2697         if (ihost->state == ISCSI_HOST_REMOVED) {
2698                 spin_unlock_irqrestore(&ihost->lock, flags);
2699                 return NULL;
2700         }
2701         ihost->num_sessions++;
2702         spin_unlock_irqrestore(&ihost->lock, flags);
2703
2704         if (!total_cmds)
2705                 total_cmds = ISCSI_DEF_XMIT_CMDS_MAX;
2706         /*
2707          * The iscsi layer needs some tasks for nop handling and tmfs,
2708          * so the cmds_max must at least be greater than ISCSI_MGMT_CMDS_MAX
2709          * + 1 command for scsi IO.
2710          */
2711         if (total_cmds < ISCSI_TOTAL_CMDS_MIN) {
2712                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2713                        "must be a power of two that is at least %d.\n",
2714                        total_cmds, ISCSI_TOTAL_CMDS_MIN);
2715                 goto dec_session_count;
2716         }
2717
2718         if (total_cmds > ISCSI_TOTAL_CMDS_MAX) {
2719                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2720                        "must be a power of 2 less than or equal to %d.\n",
2721                        cmds_max, ISCSI_TOTAL_CMDS_MAX);
2722                 total_cmds = ISCSI_TOTAL_CMDS_MAX;
2723         }
2724
2725         if (!is_power_of_2(total_cmds)) {
2726                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2727                        "must be a power of 2.\n", total_cmds);
2728                 total_cmds = rounddown_pow_of_two(total_cmds);
2729                 if (total_cmds < ISCSI_TOTAL_CMDS_MIN)
2730                         return NULL;
2731                 printk(KERN_INFO "iscsi: Rounding can_queue to %d.\n",
2732                        total_cmds);
2733         }
2734         scsi_cmds = total_cmds - ISCSI_MGMT_CMDS_MAX;
2735
2736         cls_session = iscsi_alloc_session(shost, iscsit,
2737                                           sizeof(struct iscsi_session) +
2738                                           dd_size);
2739         if (!cls_session)
2740                 goto dec_session_count;
2741         session = cls_session->dd_data;
2742         session->cls_session = cls_session;
2743         session->host = shost;
2744         session->state = ISCSI_STATE_FREE;
2745         session->fast_abort = 1;
2746         session->tgt_reset_timeout = 30;
2747         session->lu_reset_timeout = 15;
2748         session->abort_timeout = 10;
2749         session->scsi_cmds_max = scsi_cmds;
2750         session->cmds_max = total_cmds;
2751         session->queued_cmdsn = session->cmdsn = initial_cmdsn;
2752         session->exp_cmdsn = initial_cmdsn + 1;
2753         session->max_cmdsn = initial_cmdsn + 1;
2754         session->max_r2t = 1;
2755         session->tt = iscsit;
2756         session->dd_data = cls_session->dd_data + sizeof(*session);
2757         mutex_init(&session->eh_mutex);
2758         spin_lock_init(&session->lock);
2759
2760         /* initialize SCSI PDU commands pool */
2761         if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
2762                             (void***)&session->cmds,
2763                             cmd_task_size + sizeof(struct iscsi_task)))
2764                 goto cmdpool_alloc_fail;
2765
2766         /* pre-format cmds pool with ITT */
2767         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2768                 struct iscsi_task *task = session->cmds[cmd_i];
2769
2770                 if (cmd_task_size)
2771                         task->dd_data = &task[1];
2772                 task->itt = cmd_i;
2773                 task->state = ISCSI_TASK_FREE;
2774                 INIT_LIST_HEAD(&task->running);
2775         }
2776
2777         if (!try_module_get(iscsit->owner))
2778                 goto module_get_fail;
2779
2780         if (iscsi_add_session(cls_session, id))
2781                 goto cls_session_fail;
2782
2783         return cls_session;
2784
2785 cls_session_fail:
2786         module_put(iscsit->owner);
2787 module_get_fail:
2788         iscsi_pool_free(&session->cmdpool);
2789 cmdpool_alloc_fail:
2790         iscsi_free_session(cls_session);
2791 dec_session_count:
2792         iscsi_host_dec_session_cnt(shost);
2793         return NULL;
2794 }
2795 EXPORT_SYMBOL_GPL(iscsi_session_setup);
2796
2797 /**
2798  * iscsi_session_teardown - destroy session, host, and cls_session
2799  * @cls_session: iscsi session
2800  *
2801  * The driver must have called iscsi_remove_session before
2802  * calling this.
2803  */
2804 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
2805 {
2806         struct iscsi_session *session = cls_session->dd_data;
2807         struct module *owner = cls_session->transport->owner;
2808         struct Scsi_Host *shost = session->host;
2809
2810         iscsi_pool_free(&session->cmdpool);
2811
2812         kfree(session->password);
2813         kfree(session->password_in);
2814         kfree(session->username);
2815         kfree(session->username_in);
2816         kfree(session->targetname);
2817         kfree(session->initiatorname);
2818         kfree(session->ifacename);
2819
2820         iscsi_destroy_session(cls_session);
2821         iscsi_host_dec_session_cnt(shost);
2822         module_put(owner);
2823 }
2824 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
2825
2826 /**
2827  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
2828  * @cls_session: iscsi_cls_session
2829  * @dd_size: private driver data size
2830  * @conn_idx: cid
2831  */
2832 struct iscsi_cls_conn *
2833 iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size,
2834                  uint32_t conn_idx)
2835 {
2836         struct iscsi_session *session = cls_session->dd_data;
2837         struct iscsi_conn *conn;
2838         struct iscsi_cls_conn *cls_conn;
2839         char *data;
2840
2841         cls_conn = iscsi_create_conn(cls_session, sizeof(*conn) + dd_size,
2842                                      conn_idx);
2843         if (!cls_conn)
2844                 return NULL;
2845         conn = cls_conn->dd_data;
2846         memset(conn, 0, sizeof(*conn) + dd_size);
2847
2848         conn->dd_data = cls_conn->dd_data + sizeof(*conn);
2849         conn->session = session;
2850         conn->cls_conn = cls_conn;
2851         conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
2852         conn->id = conn_idx;
2853         conn->exp_statsn = 0;
2854         conn->tmf_state = TMF_INITIAL;
2855
2856         init_timer(&conn->transport_timer);
2857         conn->transport_timer.data = (unsigned long)conn;
2858         conn->transport_timer.function = iscsi_check_transport_timeouts;
2859
2860         INIT_LIST_HEAD(&conn->mgmtqueue);
2861         INIT_LIST_HEAD(&conn->cmdqueue);
2862         INIT_LIST_HEAD(&conn->requeue);
2863         INIT_WORK(&conn->xmitwork, iscsi_xmitworker);
2864
2865         /* allocate login_task used for the login/text sequences */
2866         spin_lock_bh(&session->lock);
2867         if (!kfifo_out(&session->cmdpool.queue,
2868                          (void*)&conn->login_task,
2869                          sizeof(void*))) {
2870                 spin_unlock_bh(&session->lock);
2871                 goto login_task_alloc_fail;
2872         }
2873         spin_unlock_bh(&session->lock);
2874
2875         data = (char *) __get_free_pages(GFP_KERNEL,
2876                                          get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
2877         if (!data)
2878                 goto login_task_data_alloc_fail;
2879         conn->login_task->data = conn->data = data;
2880
2881         init_timer(&conn->tmf_timer);
2882         init_waitqueue_head(&conn->ehwait);
2883
2884         return cls_conn;
2885
2886 login_task_data_alloc_fail:
2887         kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task,
2888                     sizeof(void*));
2889 login_task_alloc_fail:
2890         iscsi_destroy_conn(cls_conn);
2891         return NULL;
2892 }
2893 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
2894
2895 /**
2896  * iscsi_conn_teardown - teardown iscsi connection
2897  * cls_conn: iscsi class connection
2898  *
2899  * TODO: we may need to make this into a two step process
2900  * like scsi-mls remove + put host
2901  */
2902 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
2903 {
2904         struct iscsi_conn *conn = cls_conn->dd_data;
2905         struct iscsi_session *session = conn->session;
2906         unsigned long flags;
2907
2908         del_timer_sync(&conn->transport_timer);
2909
2910         spin_lock_bh(&session->lock);
2911         conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
2912         if (session->leadconn == conn) {
2913                 /*
2914                  * leading connection? then give up on recovery.
2915                  */
2916                 session->state = ISCSI_STATE_TERMINATE;
2917                 wake_up(&conn->ehwait);
2918         }
2919         spin_unlock_bh(&session->lock);
2920
2921         /*
2922          * Block until all in-progress commands for this connection
2923          * time out or fail.
2924          */
2925         for (;;) {
2926                 spin_lock_irqsave(session->host->host_lock, flags);
2927                 if (!session->host->host_busy) { /* OK for ERL == 0 */
2928                         spin_unlock_irqrestore(session->host->host_lock, flags);
2929                         break;
2930                 }
2931                 spin_unlock_irqrestore(session->host->host_lock, flags);
2932                 msleep_interruptible(500);
2933                 iscsi_conn_printk(KERN_INFO, conn, "iscsi conn_destroy(): "
2934                                   "host_busy %d host_failed %d\n",
2935                                   session->host->host_busy,
2936                                   session->host->host_failed);
2937                 /*
2938                  * force eh_abort() to unblock
2939                  */
2940                 wake_up(&conn->ehwait);
2941         }
2942
2943         /* flush queued up work because we free the connection below */
2944         iscsi_suspend_tx(conn);
2945
2946         spin_lock_bh(&session->lock);
2947         free_pages((unsigned long) conn->data,
2948                    get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
2949         kfree(conn->persistent_address);
2950         kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task,
2951                     sizeof(void*));
2952         if (session->leadconn == conn)
2953                 session->leadconn = NULL;
2954         spin_unlock_bh(&session->lock);
2955
2956         iscsi_destroy_conn(cls_conn);
2957 }
2958 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
2959
2960 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
2961 {
2962         struct iscsi_conn *conn = cls_conn->dd_data;
2963         struct iscsi_session *session = conn->session;
2964
2965         if (!session) {
2966                 iscsi_conn_printk(KERN_ERR, conn,
2967                                   "can't start unbound connection\n");
2968                 return -EPERM;
2969         }
2970
2971         if ((session->imm_data_en || !session->initial_r2t_en) &&
2972              session->first_burst > session->max_burst) {
2973                 iscsi_conn_printk(KERN_INFO, conn, "invalid burst lengths: "
2974                                   "first_burst %d max_burst %d\n",
2975                                   session->first_burst, session->max_burst);
2976                 return -EINVAL;
2977         }
2978
2979         if (conn->ping_timeout && !conn->recv_timeout) {
2980                 iscsi_conn_printk(KERN_ERR, conn, "invalid recv timeout of "
2981                                   "zero. Using 5 seconds\n.");
2982                 conn->recv_timeout = 5;
2983         }
2984
2985         if (conn->recv_timeout && !conn->ping_timeout) {
2986                 iscsi_conn_printk(KERN_ERR, conn, "invalid ping timeout of "
2987                                   "zero. Using 5 seconds.\n");
2988                 conn->ping_timeout = 5;
2989         }
2990
2991         spin_lock_bh(&session->lock);
2992         conn->c_stage = ISCSI_CONN_STARTED;
2993         session->state = ISCSI_STATE_LOGGED_IN;
2994         session->queued_cmdsn = session->cmdsn;
2995
2996         conn->last_recv = jiffies;
2997         conn->last_ping = jiffies;
2998         if (conn->recv_timeout && conn->ping_timeout)
2999                 mod_timer(&conn->transport_timer,
3000                           jiffies + (conn->recv_timeout * HZ));
3001
3002         switch(conn->stop_stage) {
3003         case STOP_CONN_RECOVER:
3004                 /*
3005                  * unblock eh_abort() if it is blocked. re-try all
3006                  * commands after successful recovery
3007                  */
3008                 conn->stop_stage = 0;
3009                 conn->tmf_state = TMF_INITIAL;
3010                 session->age++;
3011                 if (session->age == 16)
3012                         session->age = 0;
3013                 break;
3014         case STOP_CONN_TERM:
3015                 conn->stop_stage = 0;
3016                 break;
3017         default:
3018                 break;
3019         }
3020         spin_unlock_bh(&session->lock);
3021
3022         iscsi_unblock_session(session->cls_session);
3023         wake_up(&conn->ehwait);
3024         return 0;
3025 }
3026 EXPORT_SYMBOL_GPL(iscsi_conn_start);
3027
3028 static void
3029 fail_mgmt_tasks(struct iscsi_session *session, struct iscsi_conn *conn)
3030 {
3031         struct iscsi_task *task;
3032         int i, state;
3033
3034         for (i = 0; i < conn->session->cmds_max; i++) {
3035                 task = conn->session->cmds[i];
3036                 if (task->sc)
3037                         continue;
3038
3039                 if (task->state == ISCSI_TASK_FREE)
3040                         continue;
3041
3042                 ISCSI_DBG_SESSION(conn->session,
3043                                   "failing mgmt itt 0x%x state %d\n",
3044                                   task->itt, task->state);
3045                 state = ISCSI_TASK_ABRT_SESS_RECOV;
3046                 if (task->state == ISCSI_TASK_PENDING)
3047                         state = ISCSI_TASK_COMPLETED;
3048                 iscsi_complete_task(task, state);
3049
3050         }
3051 }
3052
3053 static void iscsi_start_session_recovery(struct iscsi_session *session,
3054                                          struct iscsi_conn *conn, int flag)
3055 {
3056         int old_stop_stage;
3057
3058         mutex_lock(&session->eh_mutex);
3059         spin_lock_bh(&session->lock);
3060         if (conn->stop_stage == STOP_CONN_TERM) {
3061                 spin_unlock_bh(&session->lock);
3062                 mutex_unlock(&session->eh_mutex);
3063                 return;
3064         }
3065
3066         /*
3067          * When this is called for the in_login state, we only want to clean
3068          * up the login task and connection. We do not need to block and set
3069          * the recovery state again
3070          */
3071         if (flag == STOP_CONN_TERM)
3072                 session->state = ISCSI_STATE_TERMINATE;
3073         else if (conn->stop_stage != STOP_CONN_RECOVER)
3074                 session->state = ISCSI_STATE_IN_RECOVERY;
3075         spin_unlock_bh(&session->lock);
3076
3077         del_timer_sync(&conn->transport_timer);
3078         iscsi_suspend_tx(conn);
3079
3080         spin_lock_bh(&session->lock);
3081         old_stop_stage = conn->stop_stage;
3082         conn->stop_stage = flag;
3083         conn->c_stage = ISCSI_CONN_STOPPED;
3084         spin_unlock_bh(&session->lock);
3085
3086         /*
3087          * for connection level recovery we should not calculate
3088          * header digest. conn->hdr_size used for optimization
3089          * in hdr_extract() and will be re-negotiated at
3090          * set_param() time.
3091          */
3092         if (flag == STOP_CONN_RECOVER) {
3093                 conn->hdrdgst_en = 0;
3094                 conn->datadgst_en = 0;
3095                 if (session->state == ISCSI_STATE_IN_RECOVERY &&
3096                     old_stop_stage != STOP_CONN_RECOVER) {
3097                         ISCSI_DBG_SESSION(session, "blocking session\n");
3098                         iscsi_block_session(session->cls_session);
3099                 }
3100         }
3101
3102         /*
3103          * flush queues.
3104          */
3105         spin_lock_bh(&session->lock);
3106         fail_scsi_tasks(conn, -1, DID_TRANSPORT_DISRUPTED);
3107         fail_mgmt_tasks(session, conn);
3108         memset(&conn->tmhdr, 0, sizeof(conn->tmhdr));
3109         spin_unlock_bh(&session->lock);
3110         mutex_unlock(&session->eh_mutex);
3111 }
3112
3113 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
3114 {
3115         struct iscsi_conn *conn = cls_conn->dd_data;
3116         struct iscsi_session *session = conn->session;
3117
3118         switch (flag) {
3119         case STOP_CONN_RECOVER:
3120         case STOP_CONN_TERM:
3121                 iscsi_start_session_recovery(session, conn, flag);
3122                 break;
3123         default:
3124                 iscsi_conn_printk(KERN_ERR, conn,
3125                                   "invalid stop flag %d\n", flag);
3126         }
3127 }
3128 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
3129
3130 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
3131                     struct iscsi_cls_conn *cls_conn, int is_leading)
3132 {
3133         struct iscsi_session *session = cls_session->dd_data;
3134         struct iscsi_conn *conn = cls_conn->dd_data;
3135
3136         spin_lock_bh(&session->lock);
3137         if (is_leading)
3138                 session->leadconn = conn;
3139         spin_unlock_bh(&session->lock);
3140
3141         /*
3142          * Unblock xmitworker(), Login Phase will pass through.
3143          */
3144         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
3145         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
3146         return 0;
3147 }
3148 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
3149
3150 static int iscsi_switch_str_param(char **param, char *new_val_buf)
3151 {
3152         char *new_val;
3153
3154         if (*param) {
3155                 if (!strcmp(*param, new_val_buf))
3156                         return 0;
3157         }
3158
3159         new_val = kstrdup(new_val_buf, GFP_NOIO);
3160         if (!new_val)
3161                 return -ENOMEM;
3162
3163         kfree(*param);
3164         *param = new_val;
3165         return 0;
3166 }
3167
3168 int iscsi_set_param(struct iscsi_cls_conn *cls_conn,
3169                     enum iscsi_param param, char *buf, int buflen)
3170 {
3171         struct iscsi_conn *conn = cls_conn->dd_data;
3172         struct iscsi_session *session = conn->session;
3173         uint32_t value;
3174
3175         switch(param) {
3176         case ISCSI_PARAM_FAST_ABORT:
3177                 sscanf(buf, "%d", &session->fast_abort);
3178                 break;
3179         case ISCSI_PARAM_ABORT_TMO:
3180                 sscanf(buf, "%d", &session->abort_timeout);
3181                 break;
3182         case ISCSI_PARAM_LU_RESET_TMO:
3183                 sscanf(buf, "%d", &session->lu_reset_timeout);
3184                 break;
3185         case ISCSI_PARAM_TGT_RESET_TMO:
3186                 sscanf(buf, "%d", &session->tgt_reset_timeout);
3187                 break;
3188         case ISCSI_PARAM_PING_TMO:
3189                 sscanf(buf, "%d", &conn->ping_timeout);
3190                 break;
3191         case ISCSI_PARAM_RECV_TMO:
3192                 sscanf(buf, "%d", &conn->recv_timeout);
3193                 break;
3194         case ISCSI_PARAM_MAX_RECV_DLENGTH:
3195                 sscanf(buf, "%d", &conn->max_recv_dlength);
3196                 break;
3197         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
3198                 sscanf(buf, "%d", &conn->max_xmit_dlength);
3199                 break;
3200         case ISCSI_PARAM_HDRDGST_EN:
3201                 sscanf(buf, "%d", &conn->hdrdgst_en);
3202                 break;
3203         case ISCSI_PARAM_DATADGST_EN:
3204                 sscanf(buf, "%d", &conn->datadgst_en);
3205                 break;
3206         case ISCSI_PARAM_INITIAL_R2T_EN:
3207                 sscanf(buf, "%d", &session->initial_r2t_en);
3208                 break;
3209         case ISCSI_PARAM_MAX_R2T:
3210                 sscanf(buf, "%d", &session->max_r2t);
3211                 break;
3212         case ISCSI_PARAM_IMM_DATA_EN:
3213                 sscanf(buf, "%d", &session->imm_data_en);
3214                 break;
3215         case ISCSI_PARAM_FIRST_BURST:
3216                 sscanf(buf, "%d", &session->first_burst);
3217                 break;
3218         case ISCSI_PARAM_MAX_BURST:
3219                 sscanf(buf, "%d", &session->max_burst);
3220                 break;
3221         case ISCSI_PARAM_PDU_INORDER_EN:
3222                 sscanf(buf, "%d", &session->pdu_inorder_en);
3223                 break;
3224         case ISCSI_PARAM_DATASEQ_INORDER_EN:
3225                 sscanf(buf, "%d", &session->dataseq_inorder_en);
3226                 break;
3227         case ISCSI_PARAM_ERL:
3228                 sscanf(buf, "%d", &session->erl);
3229                 break;
3230         case ISCSI_PARAM_IFMARKER_EN:
3231                 sscanf(buf, "%d", &value);
3232                 BUG_ON(value);
3233                 break;
3234         case ISCSI_PARAM_OFMARKER_EN:
3235                 sscanf(buf, "%d", &value);
3236                 BUG_ON(value);
3237                 break;
3238         case ISCSI_PARAM_EXP_STATSN:
3239                 sscanf(buf, "%u", &conn->exp_statsn);
3240                 break;
3241         case ISCSI_PARAM_USERNAME:
3242                 return iscsi_switch_str_param(&session->username, buf);
3243         case ISCSI_PARAM_USERNAME_IN:
3244                 return iscsi_switch_str_param(&session->username_in, buf);
3245         case ISCSI_PARAM_PASSWORD:
3246                 return iscsi_switch_str_param(&session->password, buf);
3247         case ISCSI_PARAM_PASSWORD_IN:
3248                 return iscsi_switch_str_param(&session->password_in, buf);
3249         case ISCSI_PARAM_TARGET_NAME:
3250                 return iscsi_switch_str_param(&session->targetname, buf);
3251         case ISCSI_PARAM_TPGT:
3252                 sscanf(buf, "%d", &session->tpgt);
3253                 break;
3254         case ISCSI_PARAM_PERSISTENT_PORT:
3255                 sscanf(buf, "%d", &conn->persistent_port);
3256                 break;
3257         case ISCSI_PARAM_PERSISTENT_ADDRESS:
3258                 return iscsi_switch_str_param(&conn->persistent_address, buf);
3259         case ISCSI_PARAM_IFACE_NAME:
3260                 return iscsi_switch_str_param(&session->ifacename, buf);
3261         case ISCSI_PARAM_INITIATOR_NAME:
3262                 return iscsi_switch_str_param(&session->initiatorname, buf);
3263         default:
3264                 return -ENOSYS;
3265         }
3266
3267         return 0;
3268 }
3269 EXPORT_SYMBOL_GPL(iscsi_set_param);
3270
3271 int iscsi_session_get_param(struct iscsi_cls_session *cls_session,
3272                             enum iscsi_param param, char *buf)
3273 {
3274         struct iscsi_session *session = cls_session->dd_data;
3275         int len;
3276
3277         switch(param) {
3278         case ISCSI_PARAM_FAST_ABORT:
3279                 len = sprintf(buf, "%d\n", session->fast_abort);
3280                 break;
3281         case ISCSI_PARAM_ABORT_TMO:
3282                 len = sprintf(buf, "%d\n", session->abort_timeout);
3283                 break;
3284         case ISCSI_PARAM_LU_RESET_TMO:
3285                 len = sprintf(buf, "%d\n", session->lu_reset_timeout);
3286                 break;
3287         case ISCSI_PARAM_TGT_RESET_TMO:
3288                 len = sprintf(buf, "%d\n", session->tgt_reset_timeout);
3289                 break;
3290         case ISCSI_PARAM_INITIAL_R2T_EN:
3291                 len = sprintf(buf, "%d\n", session->initial_r2t_en);
3292                 break;
3293         case ISCSI_PARAM_MAX_R2T:
3294                 len = sprintf(buf, "%hu\n", session->max_r2t);
3295                 break;
3296         case ISCSI_PARAM_IMM_DATA_EN:
3297                 len = sprintf(buf, "%d\n", session->imm_data_en);
3298                 break;
3299         case ISCSI_PARAM_FIRST_BURST:
3300                 len = sprintf(buf, "%u\n", session->first_burst);
3301                 break;
3302         case ISCSI_PARAM_MAX_BURST:
3303                 len = sprintf(buf, "%u\n", session->max_burst);
3304                 break;
3305         case ISCSI_PARAM_PDU_INORDER_EN:
3306                 len = sprintf(buf, "%d\n", session->pdu_inorder_en);
3307                 break;
3308         case ISCSI_PARAM_DATASEQ_INORDER_EN:
3309                 len = sprintf(buf, "%d\n", session->dataseq_inorder_en);
3310                 break;
3311         case ISCSI_PARAM_ERL:
3312                 len = sprintf(buf, "%d\n", session->erl);
3313                 break;
3314         case ISCSI_PARAM_TARGET_NAME:
3315                 len = sprintf(buf, "%s\n", session->targetname);
3316                 break;
3317         case ISCSI_PARAM_TPGT:
3318                 len = sprintf(buf, "%d\n", session->tpgt);
3319                 break;
3320         case ISCSI_PARAM_USERNAME:
3321                 len = sprintf(buf, "%s\n", session->username);
3322                 break;
3323         case ISCSI_PARAM_USERNAME_IN:
3324                 len = sprintf(buf, "%s\n", session->username_in);
3325                 break;
3326         case ISCSI_PARAM_PASSWORD:
3327                 len = sprintf(buf, "%s\n", session->password);
3328                 break;
3329         case ISCSI_PARAM_PASSWORD_IN:
3330                 len = sprintf(buf, "%s\n", session->password_in);
3331                 break;
3332         case ISCSI_PARAM_IFACE_NAME:
3333                 len = sprintf(buf, "%s\n", session->ifacename);
3334                 break;
3335         case ISCSI_PARAM_INITIATOR_NAME:
3336                 len = sprintf(buf, "%s\n", session->initiatorname);
3337                 break;
3338         default:
3339                 return -ENOSYS;
3340         }
3341
3342         return len;
3343 }
3344 EXPORT_SYMBOL_GPL(iscsi_session_get_param);
3345
3346 int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn,
3347                          enum iscsi_param param, char *buf)
3348 {
3349         struct iscsi_conn *conn = cls_conn->dd_data;
3350         int len;
3351
3352         switch(param) {
3353         case ISCSI_PARAM_PING_TMO:
3354                 len = sprintf(buf, "%u\n", conn->ping_timeout);
3355                 break;
3356         case ISCSI_PARAM_RECV_TMO:
3357                 len = sprintf(buf, "%u\n", conn->recv_timeout);
3358                 break;
3359         case ISCSI_PARAM_MAX_RECV_DLENGTH:
3360                 len = sprintf(buf, "%u\n", conn->max_recv_dlength);
3361                 break;
3362         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
3363                 len = sprintf(buf, "%u\n", conn->max_xmit_dlength);
3364                 break;
3365         case ISCSI_PARAM_HDRDGST_EN:
3366                 len = sprintf(buf, "%d\n", conn->hdrdgst_en);
3367                 break;
3368         case ISCSI_PARAM_DATADGST_EN:
3369                 len = sprintf(buf, "%d\n", conn->datadgst_en);
3370                 break;
3371         case ISCSI_PARAM_IFMARKER_EN:
3372                 len = sprintf(buf, "%d\n", conn->ifmarker_en);
3373                 break;
3374         case ISCSI_PARAM_OFMARKER_EN:
3375                 len = sprintf(buf, "%d\n", conn->ofmarker_en);
3376                 break;
3377         case ISCSI_PARAM_EXP_STATSN:
3378                 len = sprintf(buf, "%u\n", conn->exp_statsn);
3379                 break;
3380         case ISCSI_PARAM_PERSISTENT_PORT:
3381                 len = sprintf(buf, "%d\n", conn->persistent_port);
3382                 break;
3383         case ISCSI_PARAM_PERSISTENT_ADDRESS:
3384                 len = sprintf(buf, "%s\n", conn->persistent_address);
3385                 break;
3386         default:
3387                 return -ENOSYS;
3388         }
3389
3390         return len;
3391 }
3392 EXPORT_SYMBOL_GPL(iscsi_conn_get_param);
3393
3394 int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,
3395                          char *buf)
3396 {
3397         struct iscsi_host *ihost = shost_priv(shost);
3398         int len;
3399
3400         switch (param) {
3401         case ISCSI_HOST_PARAM_NETDEV_NAME:
3402                 len = sprintf(buf, "%s\n", ihost->netdev);
3403                 break;
3404         case ISCSI_HOST_PARAM_HWADDRESS:
3405                 len = sprintf(buf, "%s\n", ihost->hwaddress);
3406                 break;
3407         case ISCSI_HOST_PARAM_INITIATOR_NAME:
3408                 len = sprintf(buf, "%s\n", ihost->initiatorname);
3409                 break;
3410         case ISCSI_HOST_PARAM_IPADDRESS:
3411                 len = sprintf(buf, "%s\n", ihost->local_address);
3412                 break;
3413         default:
3414                 return -ENOSYS;
3415         }
3416
3417         return len;
3418 }
3419 EXPORT_SYMBOL_GPL(iscsi_host_get_param);
3420
3421 int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param,
3422                          char *buf, int buflen)
3423 {
3424         struct iscsi_host *ihost = shost_priv(shost);
3425
3426         switch (param) {
3427         case ISCSI_HOST_PARAM_NETDEV_NAME:
3428                 return iscsi_switch_str_param(&ihost->netdev, buf);
3429         case ISCSI_HOST_PARAM_HWADDRESS:
3430                 return iscsi_switch_str_param(&ihost->hwaddress, buf);
3431         case ISCSI_HOST_PARAM_INITIATOR_NAME:
3432                 return iscsi_switch_str_param(&ihost->initiatorname, buf);
3433         default:
3434                 return -ENOSYS;
3435         }
3436
3437         return 0;
3438 }
3439 EXPORT_SYMBOL_GPL(iscsi_host_set_param);
3440
3441 MODULE_AUTHOR("Mike Christie");
3442 MODULE_DESCRIPTION("iSCSI library functions");
3443 MODULE_LICENSE("GPL");