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