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