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