[SCSI] iscsi_tcp: fix padding, data digests, and IO at weird offsets
[safe/jmp/linux-2.6] / drivers / scsi / iscsi_tcp.c
1 /*
2  * iSCSI Initiator over TCP/IP Data-Path
3  *
4  * Copyright (C) 2004 Dmitry Yusupov
5  * Copyright (C) 2004 Alex Aizman
6  * Copyright (C) 2005 - 2006 Mike Christie
7  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
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
12  * by 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, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * See the file COPYING included with this distribution for more details.
21  *
22  * Credits:
23  *      Christoph Hellwig
24  *      FUJITA Tomonori
25  *      Arne Redlich
26  *      Zhenyu Wang
27  */
28
29 #include <linux/types.h>
30 #include <linux/list.h>
31 #include <linux/inet.h>
32 #include <linux/blkdev.h>
33 #include <linux/crypto.h>
34 #include <linux/delay.h>
35 #include <linux/kfifo.h>
36 #include <linux/scatterlist.h>
37 #include <linux/mutex.h>
38 #include <net/tcp.h>
39 #include <scsi/scsi_cmnd.h>
40 #include <scsi/scsi_host.h>
41 #include <scsi/scsi.h>
42 #include <scsi/scsi_transport_iscsi.h>
43
44 #include "iscsi_tcp.h"
45
46 MODULE_AUTHOR("Dmitry Yusupov <dmitry_yus@yahoo.com>, "
47               "Alex Aizman <itn780@yahoo.com>");
48 MODULE_DESCRIPTION("iSCSI/TCP data-path");
49 MODULE_LICENSE("GPL");
50 /* #define DEBUG_TCP */
51 #define DEBUG_ASSERT
52
53 #ifdef DEBUG_TCP
54 #define debug_tcp(fmt...) printk(KERN_INFO "tcp: " fmt)
55 #else
56 #define debug_tcp(fmt...)
57 #endif
58
59 #ifndef DEBUG_ASSERT
60 #ifdef BUG_ON
61 #undef BUG_ON
62 #endif
63 #define BUG_ON(expr)
64 #endif
65
66 static unsigned int iscsi_max_lun = 512;
67 module_param_named(max_lun, iscsi_max_lun, uint, S_IRUGO);
68
69 static inline void
70 iscsi_buf_init_iov(struct iscsi_buf *ibuf, char *vbuf, int size)
71 {
72         ibuf->sg.page = virt_to_page(vbuf);
73         ibuf->sg.offset = offset_in_page(vbuf);
74         ibuf->sg.length = size;
75         ibuf->sent = 0;
76         ibuf->use_sendmsg = 1;
77 }
78
79 static inline void
80 iscsi_buf_init_sg(struct iscsi_buf *ibuf, struct scatterlist *sg)
81 {
82         ibuf->sg.page = sg->page;
83         ibuf->sg.offset = sg->offset;
84         ibuf->sg.length = sg->length;
85         /*
86          * Fastpath: sg element fits into single page
87          */
88         if (sg->length + sg->offset <= PAGE_SIZE && !PageSlab(sg->page))
89                 ibuf->use_sendmsg = 0;
90         else
91                 ibuf->use_sendmsg = 1;
92         ibuf->sent = 0;
93 }
94
95 static inline int
96 iscsi_buf_left(struct iscsi_buf *ibuf)
97 {
98         int rc;
99
100         rc = ibuf->sg.length - ibuf->sent;
101         BUG_ON(rc < 0);
102         return rc;
103 }
104
105 static inline void
106 iscsi_hdr_digest(struct iscsi_conn *conn, struct iscsi_buf *buf,
107                  u8* crc)
108 {
109         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
110
111         crypto_digest_digest(tcp_conn->tx_tfm, &buf->sg, 1, crc);
112         buf->sg.length += sizeof(uint32_t);
113 }
114
115 static inline int
116 iscsi_hdr_extract(struct iscsi_tcp_conn *tcp_conn)
117 {
118         struct sk_buff *skb = tcp_conn->in.skb;
119
120         tcp_conn->in.zero_copy_hdr = 0;
121
122         if (tcp_conn->in.copy >= tcp_conn->hdr_size &&
123             tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER) {
124                 /*
125                  * Zero-copy PDU Header: using connection context
126                  * to store header pointer.
127                  */
128                 if (skb_shinfo(skb)->frag_list == NULL &&
129                     !skb_shinfo(skb)->nr_frags) {
130                         tcp_conn->in.hdr = (struct iscsi_hdr *)
131                                 ((char*)skb->data + tcp_conn->in.offset);
132                         tcp_conn->in.zero_copy_hdr = 1;
133                 } else {
134                         /* ignoring return code since we checked
135                          * in.copy before */
136                         skb_copy_bits(skb, tcp_conn->in.offset,
137                                 &tcp_conn->hdr, tcp_conn->hdr_size);
138                         tcp_conn->in.hdr = &tcp_conn->hdr;
139                 }
140                 tcp_conn->in.offset += tcp_conn->hdr_size;
141                 tcp_conn->in.copy -= tcp_conn->hdr_size;
142         } else {
143                 int hdr_remains;
144                 int copylen;
145
146                 /*
147                  * PDU header scattered across SKB's,
148                  * copying it... This'll happen quite rarely.
149                  */
150
151                 if (tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER)
152                         tcp_conn->in.hdr_offset = 0;
153
154                 hdr_remains = tcp_conn->hdr_size - tcp_conn->in.hdr_offset;
155                 BUG_ON(hdr_remains <= 0);
156
157                 copylen = min(tcp_conn->in.copy, hdr_remains);
158                 skb_copy_bits(skb, tcp_conn->in.offset,
159                         (char*)&tcp_conn->hdr + tcp_conn->in.hdr_offset,
160                         copylen);
161
162                 debug_tcp("PDU gather offset %d bytes %d in.offset %d "
163                        "in.copy %d\n", tcp_conn->in.hdr_offset, copylen,
164                        tcp_conn->in.offset, tcp_conn->in.copy);
165
166                 tcp_conn->in.offset += copylen;
167                 tcp_conn->in.copy -= copylen;
168                 if (copylen < hdr_remains)  {
169                         tcp_conn->in_progress = IN_PROGRESS_HEADER_GATHER;
170                         tcp_conn->in.hdr_offset += copylen;
171                         return -EAGAIN;
172                 }
173                 tcp_conn->in.hdr = &tcp_conn->hdr;
174                 tcp_conn->discontiguous_hdr_cnt++;
175                 tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
176         }
177
178         return 0;
179 }
180
181 /*
182  * must be called with session lock
183  */
184 static void
185 iscsi_tcp_cleanup_ctask(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
186 {
187         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
188         struct iscsi_r2t_info *r2t;
189         struct scsi_cmnd *sc;
190
191         /* flush ctask's r2t queues */
192         while (__kfifo_get(tcp_ctask->r2tqueue, (void*)&r2t, sizeof(void*))) {
193                 __kfifo_put(tcp_ctask->r2tpool.queue, (void*)&r2t,
194                             sizeof(void*));
195                 debug_scsi("iscsi_tcp_cleanup_ctask pending r2t dropped\n");
196         }
197
198         sc = ctask->sc;
199         if (unlikely(!sc))
200                 return;
201
202         tcp_ctask->xmstate = XMSTATE_IDLE;
203         tcp_ctask->r2t = NULL;
204 }
205
206 /**
207  * iscsi_data_rsp - SCSI Data-In Response processing
208  * @conn: iscsi connection
209  * @ctask: scsi command task
210  **/
211 static int
212 iscsi_data_rsp(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
213 {
214         int rc;
215         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
216         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
217         struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)tcp_conn->in.hdr;
218         struct iscsi_session *session = conn->session;
219         int datasn = be32_to_cpu(rhdr->datasn);
220
221         rc = iscsi_check_assign_cmdsn(session, (struct iscsi_nopin*)rhdr);
222         if (rc)
223                 return rc;
224         /*
225          * setup Data-In byte counter (gets decremented..)
226          */
227         ctask->data_count = tcp_conn->in.datalen;
228
229         if (tcp_conn->in.datalen == 0)
230                 return 0;
231
232         if (ctask->datasn != datasn)
233                 return ISCSI_ERR_DATASN;
234
235         ctask->datasn++;
236
237         tcp_ctask->data_offset = be32_to_cpu(rhdr->offset);
238         if (tcp_ctask->data_offset + tcp_conn->in.datalen > ctask->total_length)
239                 return ISCSI_ERR_DATA_OFFSET;
240
241         if (rhdr->flags & ISCSI_FLAG_DATA_STATUS) {
242                 struct scsi_cmnd *sc = ctask->sc;
243
244                 conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
245                 if (rhdr->flags & ISCSI_FLAG_DATA_UNDERFLOW) {
246                         int res_count = be32_to_cpu(rhdr->residual_count);
247
248                         if (res_count > 0 &&
249                             res_count <= sc->request_bufflen) {
250                                 sc->resid = res_count;
251                                 sc->result = (DID_OK << 16) | rhdr->cmd_status;
252                         } else
253                                 sc->result = (DID_BAD_TARGET << 16) |
254                                         rhdr->cmd_status;
255                 } else if (rhdr->flags & ISCSI_FLAG_DATA_OVERFLOW) {
256                         sc->resid = be32_to_cpu(rhdr->residual_count);
257                         sc->result = (DID_OK << 16) | rhdr->cmd_status;
258                 } else
259                         sc->result = (DID_OK << 16) | rhdr->cmd_status;
260         }
261
262         conn->datain_pdus_cnt++;
263         return 0;
264 }
265
266 /**
267  * iscsi_solicit_data_init - initialize first Data-Out
268  * @conn: iscsi connection
269  * @ctask: scsi command task
270  * @r2t: R2T info
271  *
272  * Notes:
273  *      Initialize first Data-Out within this R2T sequence and finds
274  *      proper data_offset within this SCSI command.
275  *
276  *      This function is called with connection lock taken.
277  **/
278 static void
279 iscsi_solicit_data_init(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
280                         struct iscsi_r2t_info *r2t)
281 {
282         struct iscsi_data *hdr;
283         struct scsi_cmnd *sc = ctask->sc;
284
285         hdr = &r2t->dtask.hdr;
286         memset(hdr, 0, sizeof(struct iscsi_data));
287         hdr->ttt = r2t->ttt;
288         hdr->datasn = cpu_to_be32(r2t->solicit_datasn);
289         r2t->solicit_datasn++;
290         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
291         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
292         hdr->itt = ctask->hdr->itt;
293         hdr->exp_statsn = r2t->exp_statsn;
294         hdr->offset = cpu_to_be32(r2t->data_offset);
295         if (r2t->data_length > conn->max_xmit_dlength) {
296                 hton24(hdr->dlength, conn->max_xmit_dlength);
297                 r2t->data_count = conn->max_xmit_dlength;
298                 hdr->flags = 0;
299         } else {
300                 hton24(hdr->dlength, r2t->data_length);
301                 r2t->data_count = r2t->data_length;
302                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
303         }
304         conn->dataout_pdus_cnt++;
305
306         r2t->sent = 0;
307
308         iscsi_buf_init_iov(&r2t->headbuf, (char*)hdr,
309                            sizeof(struct iscsi_hdr));
310
311         if (sc->use_sg) {
312                 int i, sg_count = 0;
313                 struct scatterlist *sg = sc->request_buffer;
314
315                 r2t->sg = NULL;
316                 for (i = 0; i < sc->use_sg; i++, sg += 1) {
317                         /* FIXME: prefetch ? */
318                         if (sg_count + sg->length > r2t->data_offset) {
319                                 int page_offset;
320
321                                 /* sg page found! */
322
323                                 /* offset within this page */
324                                 page_offset = r2t->data_offset - sg_count;
325
326                                 /* fill in this buffer */
327                                 iscsi_buf_init_sg(&r2t->sendbuf, sg);
328                                 r2t->sendbuf.sg.offset += page_offset;
329                                 r2t->sendbuf.sg.length -= page_offset;
330
331                                 /* xmit logic will continue with next one */
332                                 r2t->sg = sg + 1;
333                                 break;
334                         }
335                         sg_count += sg->length;
336                 }
337                 BUG_ON(r2t->sg == NULL);
338         } else {
339                 iscsi_buf_init_iov(&r2t->sendbuf,
340                             (char*)sc->request_buffer + r2t->data_offset,
341                             r2t->data_count);
342                 r2t->sg = NULL;
343         }
344 }
345
346 /**
347  * iscsi_r2t_rsp - iSCSI R2T Response processing
348  * @conn: iscsi connection
349  * @ctask: scsi command task
350  **/
351 static int
352 iscsi_r2t_rsp(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
353 {
354         struct iscsi_r2t_info *r2t;
355         struct iscsi_session *session = conn->session;
356         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
357         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
358         struct iscsi_r2t_rsp *rhdr = (struct iscsi_r2t_rsp *)tcp_conn->in.hdr;
359         int r2tsn = be32_to_cpu(rhdr->r2tsn);
360         int rc;
361
362         if (tcp_conn->in.datalen) {
363                 printk(KERN_ERR "iscsi_tcp: invalid R2t with datalen %d\n",
364                        tcp_conn->in.datalen);
365                 return ISCSI_ERR_DATALEN;
366         }
367
368         if (tcp_ctask->exp_r2tsn && tcp_ctask->exp_r2tsn != r2tsn)
369                 return ISCSI_ERR_R2TSN;
370
371         rc = iscsi_check_assign_cmdsn(session, (struct iscsi_nopin*)rhdr);
372         if (rc)
373                 return rc;
374
375         /* FIXME: use R2TSN to detect missing R2T */
376
377         /* fill-in new R2T associated with the task */
378         spin_lock(&session->lock);
379         if (!ctask->sc || ctask->mtask ||
380              session->state != ISCSI_STATE_LOGGED_IN) {
381                 printk(KERN_INFO "iscsi_tcp: dropping R2T itt %d in "
382                        "recovery...\n", ctask->itt);
383                 spin_unlock(&session->lock);
384                 return 0;
385         }
386
387         rc = __kfifo_get(tcp_ctask->r2tpool.queue, (void*)&r2t, sizeof(void*));
388         BUG_ON(!rc);
389
390         r2t->exp_statsn = rhdr->statsn;
391         r2t->data_length = be32_to_cpu(rhdr->data_length);
392         if (r2t->data_length == 0) {
393                 printk(KERN_ERR "iscsi_tcp: invalid R2T with zero data len\n");
394                 spin_unlock(&session->lock);
395                 return ISCSI_ERR_DATALEN;
396         }
397
398         if (r2t->data_length > session->max_burst)
399                 debug_scsi("invalid R2T with data len %u and max burst %u."
400                            "Attempting to execute request.\n",
401                             r2t->data_length, session->max_burst);
402
403         r2t->data_offset = be32_to_cpu(rhdr->data_offset);
404         if (r2t->data_offset + r2t->data_length > ctask->total_length) {
405                 spin_unlock(&session->lock);
406                 printk(KERN_ERR "iscsi_tcp: invalid R2T with data len %u at "
407                        "offset %u and total length %d\n", r2t->data_length,
408                        r2t->data_offset, ctask->total_length);
409                 return ISCSI_ERR_DATALEN;
410         }
411
412         r2t->ttt = rhdr->ttt; /* no flip */
413         r2t->solicit_datasn = 0;
414
415         iscsi_solicit_data_init(conn, ctask, r2t);
416
417         tcp_ctask->exp_r2tsn = r2tsn + 1;
418         tcp_ctask->xmstate |= XMSTATE_SOL_HDR;
419         __kfifo_put(tcp_ctask->r2tqueue, (void*)&r2t, sizeof(void*));
420         list_move_tail(&ctask->running, &conn->xmitqueue);
421
422         scsi_queue_work(session->host, &conn->xmitwork);
423         conn->r2t_pdus_cnt++;
424         spin_unlock(&session->lock);
425
426         return 0;
427 }
428
429 static int
430 iscsi_tcp_hdr_recv(struct iscsi_conn *conn)
431 {
432         int rc = 0, opcode, ahslen;
433         struct iscsi_hdr *hdr;
434         struct iscsi_session *session = conn->session;
435         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
436         uint32_t cdgst, rdgst = 0, itt;
437
438         hdr = tcp_conn->in.hdr;
439
440         /* verify PDU length */
441         tcp_conn->in.datalen = ntoh24(hdr->dlength);
442         if (tcp_conn->in.datalen > conn->max_recv_dlength) {
443                 printk(KERN_ERR "iscsi_tcp: datalen %d > %d\n",
444                        tcp_conn->in.datalen, conn->max_recv_dlength);
445                 return ISCSI_ERR_DATALEN;
446         }
447         tcp_conn->data_copied = 0;
448
449         /* read AHS */
450         ahslen = hdr->hlength << 2;
451         tcp_conn->in.offset += ahslen;
452         tcp_conn->in.copy -= ahslen;
453         if (tcp_conn->in.copy < 0) {
454                 printk(KERN_ERR "iscsi_tcp: can't handle AHS with length "
455                        "%d bytes\n", ahslen);
456                 return ISCSI_ERR_AHSLEN;
457         }
458
459         /* calculate read padding */
460         tcp_conn->in.padding = tcp_conn->in.datalen & (ISCSI_PAD_LEN-1);
461         if (tcp_conn->in.padding) {
462                 tcp_conn->in.padding = ISCSI_PAD_LEN - tcp_conn->in.padding;
463                 debug_scsi("read padding %d bytes\n", tcp_conn->in.padding);
464         }
465
466         if (conn->hdrdgst_en) {
467                 struct scatterlist sg;
468
469                 sg_init_one(&sg, (u8 *)hdr,
470                             sizeof(struct iscsi_hdr) + ahslen);
471                 crypto_digest_digest(tcp_conn->rx_tfm, &sg, 1, (u8 *)&cdgst);
472                 rdgst = *(uint32_t*)((char*)hdr + sizeof(struct iscsi_hdr) +
473                                      ahslen);
474                 if (cdgst != rdgst) {
475                         printk(KERN_ERR "iscsi_tcp: hdrdgst error "
476                                "recv 0x%x calc 0x%x\n", rdgst, cdgst);
477                         return ISCSI_ERR_HDR_DGST;
478                 }
479         }
480
481         opcode = hdr->opcode & ISCSI_OPCODE_MASK;
482         /* verify itt (itt encoding: age+cid+itt) */
483         rc = iscsi_verify_itt(conn, hdr, &itt);
484         if (rc == ISCSI_ERR_NO_SCSI_CMD) {
485                 tcp_conn->in.datalen = 0; /* force drop */
486                 return 0;
487         } else if (rc)
488                 return rc;
489
490         debug_tcp("opcode 0x%x offset %d copy %d ahslen %d datalen %d\n",
491                   opcode, tcp_conn->in.offset, tcp_conn->in.copy,
492                   ahslen, tcp_conn->in.datalen);
493
494         switch(opcode) {
495         case ISCSI_OP_SCSI_DATA_IN:
496                 tcp_conn->in.ctask = session->cmds[itt];
497                 rc = iscsi_data_rsp(conn, tcp_conn->in.ctask);
498                 if (rc)
499                         return rc;
500                 /* fall through */
501         case ISCSI_OP_SCSI_CMD_RSP:
502                 tcp_conn->in.ctask = session->cmds[itt];
503                 if (tcp_conn->in.datalen)
504                         goto copy_hdr;
505
506                 spin_lock(&session->lock);
507                 rc = __iscsi_complete_pdu(conn, hdr, NULL, 0);
508                 spin_unlock(&session->lock);
509                 break;
510         case ISCSI_OP_R2T:
511                 tcp_conn->in.ctask = session->cmds[itt];
512                 if (ahslen)
513                         rc = ISCSI_ERR_AHSLEN;
514                 else if (tcp_conn->in.ctask->sc->sc_data_direction ==
515                                                                 DMA_TO_DEVICE)
516                         rc = iscsi_r2t_rsp(conn, tcp_conn->in.ctask);
517                 else
518                         rc = ISCSI_ERR_PROTO;
519                 break;
520         case ISCSI_OP_LOGIN_RSP:
521         case ISCSI_OP_TEXT_RSP:
522         case ISCSI_OP_REJECT:
523         case ISCSI_OP_ASYNC_EVENT:
524                 /*
525                  * It is possible that we could get a PDU with a buffer larger
526                  * than 8K, but there are no targets that currently do this.
527                  * For now we fail until we find a vendor that needs it
528                  */
529                 if (DEFAULT_MAX_RECV_DATA_SEGMENT_LENGTH <
530                     tcp_conn->in.datalen) {
531                         printk(KERN_ERR "iscsi_tcp: received buffer of len %u "
532                               "but conn buffer is only %u (opcode %0x)\n",
533                               tcp_conn->in.datalen,
534                               DEFAULT_MAX_RECV_DATA_SEGMENT_LENGTH, opcode);
535                         rc = ISCSI_ERR_PROTO;
536                         break;
537                 }
538
539                 if (tcp_conn->in.datalen)
540                         goto copy_hdr;
541         /* fall through */
542         case ISCSI_OP_LOGOUT_RSP:
543         case ISCSI_OP_NOOP_IN:
544         case ISCSI_OP_SCSI_TMFUNC_RSP:
545                 rc = iscsi_complete_pdu(conn, hdr, NULL, 0);
546                 break;
547         default:
548                 rc = ISCSI_ERR_BAD_OPCODE;
549                 break;
550         }
551
552         return rc;
553
554 copy_hdr:
555         /*
556          * if we did zero copy for the header but we will need multiple
557          * skbs to complete the command then we have to copy the header
558          * for later use
559          */
560         if (tcp_conn->in.zero_copy_hdr && tcp_conn->in.copy <=
561            (tcp_conn->in.datalen + tcp_conn->in.padding +
562             (conn->datadgst_en ? 4 : 0))) {
563                 debug_tcp("Copying header for later use. in.copy %d in.datalen"
564                           " %d\n", tcp_conn->in.copy, tcp_conn->in.datalen);
565                 memcpy(&tcp_conn->hdr, tcp_conn->in.hdr,
566                        sizeof(struct iscsi_hdr));
567                 tcp_conn->in.hdr = &tcp_conn->hdr;
568                 tcp_conn->in.zero_copy_hdr = 0;
569         }
570         return 0;
571 }
572
573 /**
574  * iscsi_ctask_copy - copy skb bits to the destanation cmd task
575  * @conn: iscsi tcp connection
576  * @ctask: scsi command task
577  * @buf: buffer to copy to
578  * @buf_size: size of buffer
579  * @offset: offset within the buffer
580  *
581  * Notes:
582  *      The function calls skb_copy_bits() and updates per-connection and
583  *      per-cmd byte counters.
584  *
585  *      Read counters (in bytes):
586  *
587  *      conn->in.offset         offset within in progress SKB
588  *      conn->in.copy           left to copy from in progress SKB
589  *                              including padding
590  *      conn->in.copied         copied already from in progress SKB
591  *      conn->data_copied       copied already from in progress buffer
592  *      ctask->sent             total bytes sent up to the MidLayer
593  *      ctask->data_count       left to copy from in progress Data-In
594  *      buf_left                left to copy from in progress buffer
595  **/
596 static inline int
597 iscsi_ctask_copy(struct iscsi_tcp_conn *tcp_conn, struct iscsi_cmd_task *ctask,
598                 void *buf, int buf_size, int offset)
599 {
600         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
601         int buf_left = buf_size - (tcp_conn->data_copied + offset);
602         int size = min(tcp_conn->in.copy, buf_left);
603         int rc;
604
605         size = min(size, ctask->data_count);
606
607         debug_tcp("ctask_copy %d bytes at offset %d copied %d\n",
608                size, tcp_conn->in.offset, tcp_conn->in.copied);
609
610         BUG_ON(size <= 0);
611         BUG_ON(tcp_ctask->sent + size > ctask->total_length);
612
613         rc = skb_copy_bits(tcp_conn->in.skb, tcp_conn->in.offset,
614                            (char*)buf + (offset + tcp_conn->data_copied), size);
615         /* must fit into skb->len */
616         BUG_ON(rc);
617
618         tcp_conn->in.offset += size;
619         tcp_conn->in.copy -= size;
620         tcp_conn->in.copied += size;
621         tcp_conn->data_copied += size;
622         tcp_ctask->sent += size;
623         ctask->data_count -= size;
624
625         BUG_ON(tcp_conn->in.copy < 0);
626         BUG_ON(ctask->data_count < 0);
627
628         if (buf_size != (tcp_conn->data_copied + offset)) {
629                 if (!ctask->data_count) {
630                         BUG_ON(buf_size - tcp_conn->data_copied < 0);
631                         /* done with this PDU */
632                         return buf_size - tcp_conn->data_copied;
633                 }
634                 return -EAGAIN;
635         }
636
637         /* done with this buffer or with both - PDU and buffer */
638         tcp_conn->data_copied = 0;
639         return 0;
640 }
641
642 /**
643  * iscsi_tcp_copy - copy skb bits to the destanation buffer
644  * @conn: iscsi tcp connection
645  *
646  * Notes:
647  *      The function calls skb_copy_bits() and updates per-connection
648  *      byte counters.
649  **/
650 static inline int
651 iscsi_tcp_copy(struct iscsi_conn *conn)
652 {
653         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
654         int buf_size = tcp_conn->in.datalen;
655         int buf_left = buf_size - tcp_conn->data_copied;
656         int size = min(tcp_conn->in.copy, buf_left);
657         int rc;
658
659         debug_tcp("tcp_copy %d bytes at offset %d copied %d\n",
660                size, tcp_conn->in.offset, tcp_conn->data_copied);
661         BUG_ON(size <= 0);
662
663         rc = skb_copy_bits(tcp_conn->in.skb, tcp_conn->in.offset,
664                            (char*)conn->data + tcp_conn->data_copied, size);
665         BUG_ON(rc);
666
667         tcp_conn->in.offset += size;
668         tcp_conn->in.copy -= size;
669         tcp_conn->in.copied += size;
670         tcp_conn->data_copied += size;
671
672         if (buf_size != tcp_conn->data_copied)
673                 return -EAGAIN;
674
675         return 0;
676 }
677
678 static inline void
679 partial_sg_digest_update(struct crypto_tfm *tfm, struct scatterlist *sg,
680                          int offset, int length)
681 {
682         struct scatterlist temp;
683
684         memcpy(&temp, sg, sizeof(struct scatterlist));
685         temp.offset = offset;
686         temp.length = length;
687         crypto_digest_update(tfm, &temp, 1);
688 }
689
690 static void
691 iscsi_recv_digest_update(struct iscsi_tcp_conn *tcp_conn, char* buf, int len)
692 {
693         struct scatterlist tmp;
694
695         sg_init_one(&tmp, buf, len);
696         crypto_digest_update(tcp_conn->data_rx_tfm, &tmp, 1);
697 }
698
699 static int iscsi_scsi_data_in(struct iscsi_conn *conn)
700 {
701         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
702         struct iscsi_cmd_task *ctask = tcp_conn->in.ctask;
703         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
704         struct scsi_cmnd *sc = ctask->sc;
705         struct scatterlist *sg;
706         int i, offset, rc = 0;
707
708         BUG_ON((void*)ctask != sc->SCp.ptr);
709
710         /*
711          * copying Data-In into the Scsi_Cmnd
712          */
713         if (!sc->use_sg) {
714                 i = ctask->data_count;
715                 rc = iscsi_ctask_copy(tcp_conn, ctask, sc->request_buffer,
716                                       sc->request_bufflen,
717                                       tcp_ctask->data_offset);
718                 if (rc == -EAGAIN)
719                         return rc;
720                 if (conn->datadgst_en)
721                         iscsi_recv_digest_update(tcp_conn, sc->request_buffer,
722                                                  i);
723                 rc = 0;
724                 goto done;
725         }
726
727         offset = tcp_ctask->data_offset;
728         sg = sc->request_buffer;
729
730         if (tcp_ctask->data_offset)
731                 for (i = 0; i < tcp_ctask->sg_count; i++)
732                         offset -= sg[i].length;
733         /* we've passed through partial sg*/
734         if (offset < 0)
735                 offset = 0;
736
737         for (i = tcp_ctask->sg_count; i < sc->use_sg; i++) {
738                 char *dest;
739
740                 dest = kmap_atomic(sg[i].page, KM_SOFTIRQ0);
741                 rc = iscsi_ctask_copy(tcp_conn, ctask, dest + sg[i].offset,
742                                       sg[i].length, offset);
743                 kunmap_atomic(dest, KM_SOFTIRQ0);
744                 if (rc == -EAGAIN)
745                         /* continue with the next SKB/PDU */
746                         return rc;
747                 if (!rc) {
748                         if (conn->datadgst_en) {
749                                 if (!offset)
750                                         crypto_digest_update(
751                                                         tcp_conn->data_rx_tfm,
752                                                         &sg[i], 1);
753                                 else
754                                         partial_sg_digest_update(
755                                                         tcp_conn->data_rx_tfm,
756                                                         &sg[i],
757                                                         sg[i].offset + offset,
758                                                         sg[i].length - offset);
759                         }
760                         offset = 0;
761                         tcp_ctask->sg_count++;
762                 }
763
764                 if (!ctask->data_count) {
765                         if (rc && conn->datadgst_en)
766                                 /*
767                                  * data-in is complete, but buffer not...
768                                  */
769                                 partial_sg_digest_update(tcp_conn->data_rx_tfm,
770                                                 &sg[i],
771                                                 sg[i].offset, sg[i].length-rc);
772                         rc = 0;
773                         break;
774                 }
775
776                 if (!tcp_conn->in.copy)
777                         return -EAGAIN;
778         }
779         BUG_ON(ctask->data_count);
780
781 done:
782         /* check for non-exceptional status */
783         if (tcp_conn->in.hdr->flags & ISCSI_FLAG_DATA_STATUS) {
784                 debug_scsi("done [sc %lx res %d itt 0x%x flags 0x%x]\n",
785                            (long)sc, sc->result, ctask->itt,
786                            tcp_conn->in.hdr->flags);
787                 spin_lock(&conn->session->lock);
788                 __iscsi_complete_pdu(conn, tcp_conn->in.hdr, NULL, 0);
789                 spin_unlock(&conn->session->lock);
790         }
791
792         return rc;
793 }
794
795 static int
796 iscsi_data_recv(struct iscsi_conn *conn)
797 {
798         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
799         int rc = 0, opcode;
800
801         opcode = tcp_conn->in.hdr->opcode & ISCSI_OPCODE_MASK;
802         switch (opcode) {
803         case ISCSI_OP_SCSI_DATA_IN:
804                 rc = iscsi_scsi_data_in(conn);
805                 break;
806         case ISCSI_OP_SCSI_CMD_RSP:
807         case ISCSI_OP_TEXT_RSP:
808         case ISCSI_OP_LOGIN_RSP:
809         case ISCSI_OP_ASYNC_EVENT:
810         case ISCSI_OP_REJECT:
811                 /*
812                  * Collect data segment to the connection's data
813                  * placeholder
814                  */
815                 if (iscsi_tcp_copy(conn)) {
816                         rc = -EAGAIN;
817                         goto exit;
818                 }
819
820                 rc = iscsi_complete_pdu(conn, tcp_conn->in.hdr, conn->data,
821                                         tcp_conn->in.datalen);
822                 if (!rc && conn->datadgst_en && opcode != ISCSI_OP_LOGIN_RSP)
823                         iscsi_recv_digest_update(tcp_conn, conn->data,
824                                                 tcp_conn->in.datalen);
825                 break;
826         default:
827                 BUG_ON(1);
828         }
829 exit:
830         return rc;
831 }
832
833 /**
834  * iscsi_tcp_data_recv - TCP receive in sendfile fashion
835  * @rd_desc: read descriptor
836  * @skb: socket buffer
837  * @offset: offset in skb
838  * @len: skb->len - offset
839  **/
840 static int
841 iscsi_tcp_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
842                 unsigned int offset, size_t len)
843 {
844         int rc;
845         struct iscsi_conn *conn = rd_desc->arg.data;
846         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
847         int processed;
848         char pad[ISCSI_PAD_LEN];
849         struct scatterlist sg;
850
851         /*
852          * Save current SKB and its offset in the corresponding
853          * connection context.
854          */
855         tcp_conn->in.copy = skb->len - offset;
856         tcp_conn->in.offset = offset;
857         tcp_conn->in.skb = skb;
858         tcp_conn->in.len = tcp_conn->in.copy;
859         BUG_ON(tcp_conn->in.copy <= 0);
860         debug_tcp("in %d bytes\n", tcp_conn->in.copy);
861
862 more:
863         tcp_conn->in.copied = 0;
864         rc = 0;
865
866         if (unlikely(conn->suspend_rx)) {
867                 debug_tcp("conn %d Rx suspended!\n", conn->id);
868                 return 0;
869         }
870
871         if (tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER ||
872             tcp_conn->in_progress == IN_PROGRESS_HEADER_GATHER) {
873                 rc = iscsi_hdr_extract(tcp_conn);
874                 if (rc) {
875                        if (rc == -EAGAIN)
876                                 goto nomore;
877                        else {
878                                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
879                                 return 0;
880                        }
881                 }
882
883                 /*
884                  * Verify and process incoming PDU header.
885                  */
886                 rc = iscsi_tcp_hdr_recv(conn);
887                 if (!rc && tcp_conn->in.datalen) {
888                         if (conn->datadgst_en) {
889                                 BUG_ON(!tcp_conn->data_rx_tfm);
890                                 crypto_digest_init(tcp_conn->data_rx_tfm);
891                         }
892                         tcp_conn->in_progress = IN_PROGRESS_DATA_RECV;
893                 } else if (rc) {
894                         iscsi_conn_failure(conn, rc);
895                         return 0;
896                 }
897         }
898
899         if (tcp_conn->in_progress == IN_PROGRESS_DDIGEST_RECV) {
900                 uint32_t recv_digest;
901
902                 debug_tcp("extra data_recv offset %d copy %d\n",
903                           tcp_conn->in.offset, tcp_conn->in.copy);
904                 skb_copy_bits(tcp_conn->in.skb, tcp_conn->in.offset,
905                                 &recv_digest, 4);
906                 tcp_conn->in.offset += 4;
907                 tcp_conn->in.copy -= 4;
908                 if (recv_digest != tcp_conn->in.datadgst) {
909                         debug_tcp("iscsi_tcp: data digest error!"
910                                   "0x%x != 0x%x\n", recv_digest,
911                                   tcp_conn->in.datadgst);
912                         iscsi_conn_failure(conn, ISCSI_ERR_DATA_DGST);
913                         return 0;
914                 } else {
915                         debug_tcp("iscsi_tcp: data digest match!"
916                                   "0x%x == 0x%x\n", recv_digest,
917                                   tcp_conn->in.datadgst);
918                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
919                 }
920         }
921
922         if (tcp_conn->in_progress == IN_PROGRESS_DATA_RECV &&
923            tcp_conn->in.copy) {
924
925                 debug_tcp("data_recv offset %d copy %d\n",
926                        tcp_conn->in.offset, tcp_conn->in.copy);
927
928                 rc = iscsi_data_recv(conn);
929                 if (rc) {
930                         if (rc == -EAGAIN)
931                                 goto again;
932                         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
933                         return 0;
934                 }
935                 tcp_conn->in.copy -= tcp_conn->in.padding;
936                 tcp_conn->in.offset += tcp_conn->in.padding;
937                 if (conn->datadgst_en) {
938                         if (tcp_conn->in.padding) {
939                                 debug_tcp("padding -> %d\n",
940                                           tcp_conn->in.padding);
941                                 memset(pad, 0, tcp_conn->in.padding);
942                                 sg_init_one(&sg, pad, tcp_conn->in.padding);
943                                 crypto_digest_update(tcp_conn->data_rx_tfm,
944                                                      &sg, 1);
945                         }
946                         crypto_digest_final(tcp_conn->data_rx_tfm,
947                                             (u8 *) & tcp_conn->in.datadgst);
948                         debug_tcp("rx digest 0x%x\n", tcp_conn->in.datadgst);
949                         tcp_conn->in_progress = IN_PROGRESS_DDIGEST_RECV;
950                 } else
951                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
952         }
953
954         debug_tcp("f, processed %d from out of %d padding %d\n",
955                tcp_conn->in.offset - offset, (int)len, tcp_conn->in.padding);
956         BUG_ON(tcp_conn->in.offset - offset > len);
957
958         if (tcp_conn->in.offset - offset != len) {
959                 debug_tcp("continue to process %d bytes\n",
960                        (int)len - (tcp_conn->in.offset - offset));
961                 goto more;
962         }
963
964 nomore:
965         processed = tcp_conn->in.offset - offset;
966         BUG_ON(processed == 0);
967         return processed;
968
969 again:
970         processed = tcp_conn->in.offset - offset;
971         debug_tcp("c, processed %d from out of %d rd_desc_cnt %d\n",
972                   processed, (int)len, (int)rd_desc->count);
973         BUG_ON(processed == 0);
974         BUG_ON(processed > len);
975
976         conn->rxdata_octets += processed;
977         return processed;
978 }
979
980 static void
981 iscsi_tcp_data_ready(struct sock *sk, int flag)
982 {
983         struct iscsi_conn *conn = sk->sk_user_data;
984         read_descriptor_t rd_desc;
985
986         read_lock(&sk->sk_callback_lock);
987
988         /*
989          * Use rd_desc to pass 'conn' to iscsi_tcp_data_recv.
990          * We set count to 1 because we want the network layer to
991          * hand us all the skbs that are available. iscsi_tcp_data_recv
992          * handled pdus that cross buffers or pdus that still need data.
993          */
994         rd_desc.arg.data = conn;
995         rd_desc.count = 1;
996         tcp_read_sock(sk, &rd_desc, iscsi_tcp_data_recv);
997
998         read_unlock(&sk->sk_callback_lock);
999 }
1000
1001 static void
1002 iscsi_tcp_state_change(struct sock *sk)
1003 {
1004         struct iscsi_tcp_conn *tcp_conn;
1005         struct iscsi_conn *conn;
1006         struct iscsi_session *session;
1007         void (*old_state_change)(struct sock *);
1008
1009         read_lock(&sk->sk_callback_lock);
1010
1011         conn = (struct iscsi_conn*)sk->sk_user_data;
1012         session = conn->session;
1013
1014         if ((sk->sk_state == TCP_CLOSE_WAIT ||
1015              sk->sk_state == TCP_CLOSE) &&
1016             !atomic_read(&sk->sk_rmem_alloc)) {
1017                 debug_tcp("iscsi_tcp_state_change: TCP_CLOSE|TCP_CLOSE_WAIT\n");
1018                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1019         }
1020
1021         tcp_conn = conn->dd_data;
1022         old_state_change = tcp_conn->old_state_change;
1023
1024         read_unlock(&sk->sk_callback_lock);
1025
1026         old_state_change(sk);
1027 }
1028
1029 /**
1030  * iscsi_write_space - Called when more output buffer space is available
1031  * @sk: socket space is available for
1032  **/
1033 static void
1034 iscsi_write_space(struct sock *sk)
1035 {
1036         struct iscsi_conn *conn = (struct iscsi_conn*)sk->sk_user_data;
1037         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1038
1039         tcp_conn->old_write_space(sk);
1040         debug_tcp("iscsi_write_space: cid %d\n", conn->id);
1041         scsi_queue_work(conn->session->host, &conn->xmitwork);
1042 }
1043
1044 static void
1045 iscsi_conn_set_callbacks(struct iscsi_conn *conn)
1046 {
1047         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1048         struct sock *sk = tcp_conn->sock->sk;
1049
1050         /* assign new callbacks */
1051         write_lock_bh(&sk->sk_callback_lock);
1052         sk->sk_user_data = conn;
1053         tcp_conn->old_data_ready = sk->sk_data_ready;
1054         tcp_conn->old_state_change = sk->sk_state_change;
1055         tcp_conn->old_write_space = sk->sk_write_space;
1056         sk->sk_data_ready = iscsi_tcp_data_ready;
1057         sk->sk_state_change = iscsi_tcp_state_change;
1058         sk->sk_write_space = iscsi_write_space;
1059         write_unlock_bh(&sk->sk_callback_lock);
1060 }
1061
1062 static void
1063 iscsi_conn_restore_callbacks(struct iscsi_tcp_conn *tcp_conn)
1064 {
1065         struct sock *sk = tcp_conn->sock->sk;
1066
1067         /* restore socket callbacks, see also: iscsi_conn_set_callbacks() */
1068         write_lock_bh(&sk->sk_callback_lock);
1069         sk->sk_user_data    = NULL;
1070         sk->sk_data_ready   = tcp_conn->old_data_ready;
1071         sk->sk_state_change = tcp_conn->old_state_change;
1072         sk->sk_write_space  = tcp_conn->old_write_space;
1073         sk->sk_no_check  = 0;
1074         write_unlock_bh(&sk->sk_callback_lock);
1075 }
1076
1077 /**
1078  * iscsi_send - generic send routine
1079  * @sk: kernel's socket
1080  * @buf: buffer to write from
1081  * @size: actual size to write
1082  * @flags: socket's flags
1083  */
1084 static inline int
1085 iscsi_send(struct iscsi_conn *conn, struct iscsi_buf *buf, int size, int flags)
1086 {
1087         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1088         struct socket *sk = tcp_conn->sock;
1089         int offset = buf->sg.offset + buf->sent, res;
1090
1091         /*
1092          * if we got use_sg=0 or are sending something we kmallocd
1093          * then we did not have to do kmap (kmap returns page_address)
1094          *
1095          * if we got use_sg > 0, but had to drop down, we do not
1096          * set clustering so this should only happen for that
1097          * slab case.
1098          */
1099         if (buf->use_sendmsg)
1100                 res = sock_no_sendpage(sk, buf->sg.page, offset, size, flags);
1101         else
1102                 res = tcp_conn->sendpage(sk, buf->sg.page, offset, size, flags);
1103
1104         if (res >= 0) {
1105                 conn->txdata_octets += res;
1106                 buf->sent += res;
1107                 return res;
1108         }
1109
1110         tcp_conn->sendpage_failures_cnt++;
1111         if (res == -EAGAIN)
1112                 res = -ENOBUFS;
1113         else
1114                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1115         return res;
1116 }
1117
1118 /**
1119  * iscsi_sendhdr - send PDU Header via tcp_sendpage()
1120  * @conn: iscsi connection
1121  * @buf: buffer to write from
1122  * @datalen: lenght of data to be sent after the header
1123  *
1124  * Notes:
1125  *      (Tx, Fast Path)
1126  **/
1127 static inline int
1128 iscsi_sendhdr(struct iscsi_conn *conn, struct iscsi_buf *buf, int datalen)
1129 {
1130         int flags = 0; /* MSG_DONTWAIT; */
1131         int res, size;
1132
1133         size = buf->sg.length - buf->sent;
1134         BUG_ON(buf->sent + size > buf->sg.length);
1135         if (buf->sent + size != buf->sg.length || datalen)
1136                 flags |= MSG_MORE;
1137
1138         res = iscsi_send(conn, buf, size, flags);
1139         debug_tcp("sendhdr %d bytes, sent %d res %d\n", size, buf->sent, res);
1140         if (res >= 0) {
1141                 if (size != res)
1142                         return -EAGAIN;
1143                 return 0;
1144         }
1145
1146         return res;
1147 }
1148
1149 /**
1150  * iscsi_sendpage - send one page of iSCSI Data-Out.
1151  * @conn: iscsi connection
1152  * @buf: buffer to write from
1153  * @count: remaining data
1154  * @sent: number of bytes sent
1155  *
1156  * Notes:
1157  *      (Tx, Fast Path)
1158  **/
1159 static inline int
1160 iscsi_sendpage(struct iscsi_conn *conn, struct iscsi_buf *buf,
1161                int *count, int *sent)
1162 {
1163         int flags = 0; /* MSG_DONTWAIT; */
1164         int res, size;
1165
1166         size = buf->sg.length - buf->sent;
1167         BUG_ON(buf->sent + size > buf->sg.length);
1168         if (size > *count)
1169                 size = *count;
1170         if (buf->sent + size != buf->sg.length || *count != size)
1171                 flags |= MSG_MORE;
1172
1173         res = iscsi_send(conn, buf, size, flags);
1174         debug_tcp("sendpage: %d bytes, sent %d left %d sent %d res %d\n",
1175                   size, buf->sent, *count, *sent, res);
1176         if (res >= 0) {
1177                 *count -= res;
1178                 *sent += res;
1179                 if (size != res)
1180                         return -EAGAIN;
1181                 return 0;
1182         }
1183
1184         return res;
1185 }
1186
1187 static inline void
1188 iscsi_data_digest_init(struct iscsi_tcp_conn *tcp_conn,
1189                       struct iscsi_tcp_cmd_task *tcp_ctask)
1190 {
1191         crypto_digest_init(tcp_conn->data_tx_tfm);
1192         tcp_ctask->digest_count = 4;
1193 }
1194
1195 /**
1196  * iscsi_solicit_data_cont - initialize next Data-Out
1197  * @conn: iscsi connection
1198  * @ctask: scsi command task
1199  * @r2t: R2T info
1200  * @left: bytes left to transfer
1201  *
1202  * Notes:
1203  *      Initialize next Data-Out within this R2T sequence and continue
1204  *      to process next Scatter-Gather element(if any) of this SCSI command.
1205  *
1206  *      Called under connection lock.
1207  **/
1208 static void
1209 iscsi_solicit_data_cont(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1210                         struct iscsi_r2t_info *r2t, int left)
1211 {
1212         struct iscsi_data *hdr;
1213         struct scsi_cmnd *sc = ctask->sc;
1214         int new_offset;
1215
1216         hdr = &r2t->dtask.hdr;
1217         memset(hdr, 0, sizeof(struct iscsi_data));
1218         hdr->ttt = r2t->ttt;
1219         hdr->datasn = cpu_to_be32(r2t->solicit_datasn);
1220         r2t->solicit_datasn++;
1221         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
1222         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
1223         hdr->itt = ctask->hdr->itt;
1224         hdr->exp_statsn = r2t->exp_statsn;
1225         new_offset = r2t->data_offset + r2t->sent;
1226         hdr->offset = cpu_to_be32(new_offset);
1227         if (left > conn->max_xmit_dlength) {
1228                 hton24(hdr->dlength, conn->max_xmit_dlength);
1229                 r2t->data_count = conn->max_xmit_dlength;
1230         } else {
1231                 hton24(hdr->dlength, left);
1232                 r2t->data_count = left;
1233                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
1234         }
1235         conn->dataout_pdus_cnt++;
1236
1237         iscsi_buf_init_iov(&r2t->headbuf, (char*)hdr,
1238                            sizeof(struct iscsi_hdr));
1239
1240         if (iscsi_buf_left(&r2t->sendbuf))
1241                 return;
1242
1243         if (sc->use_sg) {
1244                 iscsi_buf_init_sg(&r2t->sendbuf, r2t->sg);
1245                 r2t->sg += 1;
1246         } else {
1247                 iscsi_buf_init_iov(&r2t->sendbuf,
1248                             (char*)sc->request_buffer + new_offset,
1249                             r2t->data_count);
1250                 r2t->sg = NULL;
1251         }
1252 }
1253
1254 static void iscsi_set_padding(struct iscsi_tcp_cmd_task *tcp_ctask,
1255                               unsigned long len)
1256 {
1257         tcp_ctask->pad_count = len & (ISCSI_PAD_LEN - 1);
1258         if (!tcp_ctask->pad_count)
1259                 return;
1260
1261         tcp_ctask->pad_count = ISCSI_PAD_LEN - tcp_ctask->pad_count;
1262         debug_scsi("write padding %d bytes\n", tcp_ctask->pad_count);
1263         tcp_ctask->xmstate |= XMSTATE_W_PAD;
1264 }
1265
1266 /**
1267  * iscsi_tcp_cmd_init - Initialize iSCSI SCSI_READ or SCSI_WRITE commands
1268  * @conn: iscsi connection
1269  * @ctask: scsi command task
1270  * @sc: scsi command
1271  **/
1272 static void
1273 iscsi_tcp_cmd_init(struct iscsi_cmd_task *ctask)
1274 {
1275         struct scsi_cmnd *sc = ctask->sc;
1276         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1277
1278         BUG_ON(__kfifo_len(tcp_ctask->r2tqueue));
1279
1280         tcp_ctask->sent = 0;
1281         tcp_ctask->sg_count = 0;
1282
1283         if (sc->sc_data_direction == DMA_TO_DEVICE) {
1284                 tcp_ctask->xmstate = XMSTATE_W_HDR;
1285                 tcp_ctask->exp_r2tsn = 0;
1286                 BUG_ON(ctask->total_length == 0);
1287
1288                 if (sc->use_sg) {
1289                         struct scatterlist *sg = sc->request_buffer;
1290
1291                         iscsi_buf_init_sg(&tcp_ctask->sendbuf, sg);
1292                         tcp_ctask->sg = sg + 1;
1293                         tcp_ctask->bad_sg = sg + sc->use_sg;
1294                 } else {
1295                         iscsi_buf_init_iov(&tcp_ctask->sendbuf,
1296                                            sc->request_buffer,
1297                                            sc->request_bufflen);
1298                         tcp_ctask->sg = NULL;
1299                         tcp_ctask->bad_sg = NULL;
1300                 }
1301                 debug_scsi("cmd [itt 0x%x total %d imm_data %d "
1302                            "unsol count %d, unsol offset %d]\n",
1303                            ctask->itt, ctask->total_length, ctask->imm_count,
1304                            ctask->unsol_count, ctask->unsol_offset);
1305         } else
1306                 tcp_ctask->xmstate = XMSTATE_R_HDR;
1307
1308         iscsi_buf_init_iov(&tcp_ctask->headbuf, (char*)ctask->hdr,
1309                             sizeof(struct iscsi_hdr));
1310 }
1311
1312 /**
1313  * iscsi_tcp_mtask_xmit - xmit management(immediate) task
1314  * @conn: iscsi connection
1315  * @mtask: task management task
1316  *
1317  * Notes:
1318  *      The function can return -EAGAIN in which case caller must
1319  *      call it again later, or recover. '0' return code means successful
1320  *      xmit.
1321  *
1322  *      Management xmit state machine consists of two states:
1323  *              IN_PROGRESS_IMM_HEAD - PDU Header xmit in progress
1324  *              IN_PROGRESS_IMM_DATA - PDU Data xmit in progress
1325  **/
1326 static int
1327 iscsi_tcp_mtask_xmit(struct iscsi_conn *conn, struct iscsi_mgmt_task *mtask)
1328 {
1329         struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
1330         int rc;
1331
1332         debug_scsi("mtask deq [cid %d state %x itt 0x%x]\n",
1333                 conn->id, tcp_mtask->xmstate, mtask->itt);
1334
1335         if (tcp_mtask->xmstate & XMSTATE_IMM_HDR) {
1336                 tcp_mtask->xmstate &= ~XMSTATE_IMM_HDR;
1337                 if (mtask->data_count)
1338                         tcp_mtask->xmstate |= XMSTATE_IMM_DATA;
1339                 if (conn->c_stage != ISCSI_CONN_INITIAL_STAGE &&
1340                     conn->stop_stage != STOP_CONN_RECOVER &&
1341                     conn->hdrdgst_en)
1342                         iscsi_hdr_digest(conn, &tcp_mtask->headbuf,
1343                                         (u8*)tcp_mtask->hdrext);
1344                 rc = iscsi_sendhdr(conn, &tcp_mtask->headbuf,
1345                                    mtask->data_count);
1346                 if (rc) {
1347                         tcp_mtask->xmstate |= XMSTATE_IMM_HDR;
1348                         if (mtask->data_count)
1349                                 tcp_mtask->xmstate &= ~XMSTATE_IMM_DATA;
1350                         return rc;
1351                 }
1352         }
1353
1354         if (tcp_mtask->xmstate & XMSTATE_IMM_DATA) {
1355                 BUG_ON(!mtask->data_count);
1356                 tcp_mtask->xmstate &= ~XMSTATE_IMM_DATA;
1357                 /* FIXME: implement.
1358                  * Virtual buffer could be spreaded across multiple pages...
1359                  */
1360                 do {
1361                         int rc;
1362
1363                         rc = iscsi_sendpage(conn, &tcp_mtask->sendbuf,
1364                                         &mtask->data_count, &tcp_mtask->sent);
1365                         if (rc) {
1366                                 tcp_mtask->xmstate |= XMSTATE_IMM_DATA;
1367                                 return rc;
1368                         }
1369                 } while (mtask->data_count);
1370         }
1371
1372         BUG_ON(tcp_mtask->xmstate != XMSTATE_IDLE);
1373         if (mtask->hdr->itt == cpu_to_be32(ISCSI_RESERVED_TAG)) {
1374                 struct iscsi_session *session = conn->session;
1375
1376                 spin_lock_bh(&session->lock);
1377                 list_del(&conn->mtask->running);
1378                 __kfifo_put(session->mgmtpool.queue, (void*)&conn->mtask,
1379                             sizeof(void*));
1380                 spin_unlock_bh(&session->lock);
1381         }
1382         return 0;
1383 }
1384
1385 static inline int
1386 iscsi_send_read_hdr(struct iscsi_conn *conn,
1387                     struct iscsi_tcp_cmd_task *tcp_ctask)
1388 {
1389         int rc;
1390
1391         tcp_ctask->xmstate &= ~XMSTATE_R_HDR;
1392         if (conn->hdrdgst_en)
1393                 iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1394                                  (u8*)tcp_ctask->hdrext);
1395         rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, 0);
1396         if (!rc) {
1397                 BUG_ON(tcp_ctask->xmstate != XMSTATE_IDLE);
1398                 return 0; /* wait for Data-In */
1399         }
1400         tcp_ctask->xmstate |= XMSTATE_R_HDR;
1401         return rc;
1402 }
1403
1404 static inline int
1405 iscsi_send_write_hdr(struct iscsi_conn *conn,
1406                      struct iscsi_cmd_task *ctask)
1407 {
1408         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1409         int rc;
1410
1411         tcp_ctask->xmstate &= ~XMSTATE_W_HDR;
1412         if (conn->hdrdgst_en)
1413                 iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1414                                  (u8*)tcp_ctask->hdrext);
1415         rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, ctask->imm_count);
1416         if (rc) {
1417                 tcp_ctask->xmstate |= XMSTATE_W_HDR;
1418                 return rc;
1419         }
1420
1421         if (ctask->imm_count) {
1422                 tcp_ctask->xmstate |= XMSTATE_IMM_DATA;
1423                 iscsi_set_padding(tcp_ctask, ctask->imm_count);
1424
1425                 if (ctask->conn->datadgst_en) {
1426                         iscsi_data_digest_init(ctask->conn->dd_data, tcp_ctask);
1427                         tcp_ctask->immdigest = 0;
1428                 }
1429         }
1430
1431         if (ctask->unsol_count)
1432                 tcp_ctask->xmstate |= XMSTATE_UNS_HDR | XMSTATE_UNS_INIT;
1433         return 0;
1434 }
1435
1436 static int
1437 iscsi_send_padding(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1438 {
1439         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1440         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1441         int sent = 0, rc;
1442
1443         if (tcp_ctask->xmstate & XMSTATE_W_PAD) {
1444                 iscsi_buf_init_iov(&tcp_ctask->sendbuf, (char*)&tcp_ctask->pad,
1445                                    tcp_ctask->pad_count);
1446                 if (conn->datadgst_en)
1447                         crypto_digest_update(tcp_conn->data_tx_tfm,
1448                                              &tcp_ctask->sendbuf.sg, 1);
1449         } else if (!(tcp_ctask->xmstate & XMSTATE_W_RESEND_PAD))
1450                 return 0;
1451
1452         tcp_ctask->xmstate &= ~XMSTATE_W_PAD;
1453         tcp_ctask->xmstate &= ~XMSTATE_W_RESEND_PAD;
1454         debug_scsi("sending %d pad bytes for itt 0x%x\n",
1455                    tcp_ctask->pad_count, ctask->itt);
1456         rc = iscsi_sendpage(conn, &tcp_ctask->sendbuf, &tcp_ctask->pad_count,
1457                            &sent);
1458         if (rc) {
1459                 debug_scsi("padding send failed %d\n", rc);
1460                 tcp_ctask->xmstate |= XMSTATE_W_RESEND_PAD;
1461         }
1462         return rc;
1463 }
1464
1465 static int
1466 iscsi_send_digest(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1467                         struct iscsi_buf *buf, uint32_t *digest)
1468 {
1469         struct iscsi_tcp_cmd_task *tcp_ctask;
1470         struct iscsi_tcp_conn *tcp_conn;
1471         int rc, sent = 0;
1472
1473         if (!conn->datadgst_en)
1474                 return 0;
1475
1476         tcp_ctask = ctask->dd_data;
1477         tcp_conn = conn->dd_data;
1478
1479         if (!(tcp_ctask->xmstate & XMSTATE_W_RESEND_DATA_DIGEST)) {
1480                 crypto_digest_final(tcp_conn->data_tx_tfm, (u8*)digest);
1481                 iscsi_buf_init_iov(buf, (char*)digest, 4);
1482         }
1483         tcp_ctask->xmstate &= ~XMSTATE_W_RESEND_DATA_DIGEST;
1484
1485         rc = iscsi_sendpage(conn, buf, &tcp_ctask->digest_count, &sent);
1486         if (!rc)
1487                 debug_scsi("sent digest 0x%x for itt 0x%x\n", *digest,
1488                           ctask->itt);
1489         else {
1490                 debug_scsi("sending digest 0x%x failed for itt 0x%x!\n",
1491                           *digest, ctask->itt);
1492                 tcp_ctask->xmstate |= XMSTATE_W_RESEND_DATA_DIGEST;
1493         }
1494         return rc;
1495 }
1496
1497 static int
1498 iscsi_send_data(struct iscsi_cmd_task *ctask, struct iscsi_buf *sendbuf,
1499                 struct scatterlist **sg, int *sent, int *count,
1500                 struct iscsi_buf *digestbuf, uint32_t *digest)
1501 {
1502         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1503         struct iscsi_conn *conn = ctask->conn;
1504         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1505         int rc, buf_sent, offset;
1506
1507         while (*count) {
1508                 buf_sent = 0;
1509                 offset = sendbuf->sent;
1510
1511                 rc = iscsi_sendpage(conn, sendbuf, count, &buf_sent);
1512                 *sent = *sent + buf_sent;
1513                 if (buf_sent && conn->datadgst_en)
1514                         partial_sg_digest_update(tcp_conn->data_tx_tfm,
1515                                 &sendbuf->sg, sendbuf->sg.offset + offset,
1516                                 buf_sent);
1517                 if (!iscsi_buf_left(sendbuf) && *sg != tcp_ctask->bad_sg) {
1518                         iscsi_buf_init_sg(sendbuf, *sg);
1519                         *sg = *sg + 1;
1520                 }
1521
1522                 if (rc)
1523                         return rc;
1524         }
1525
1526         rc = iscsi_send_padding(conn, ctask);
1527         if (rc)
1528                 return rc;
1529
1530         return iscsi_send_digest(conn, ctask, digestbuf, digest);
1531 }
1532
1533 static int
1534 iscsi_send_unsol_hdr(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1535 {
1536         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1537         struct iscsi_data_task *dtask;
1538         int rc;
1539
1540         tcp_ctask->xmstate |= XMSTATE_UNS_DATA;
1541         if (tcp_ctask->xmstate & XMSTATE_UNS_INIT) {
1542                 dtask = &tcp_ctask->unsol_dtask;
1543
1544                 iscsi_prep_unsolicit_data_pdu(ctask, &dtask->hdr);
1545                 iscsi_buf_init_iov(&tcp_ctask->headbuf, (char*)&dtask->hdr,
1546                                    sizeof(struct iscsi_hdr));
1547                 if (conn->hdrdgst_en)
1548                         iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1549                                         (u8*)dtask->hdrext);
1550                 if (conn->datadgst_en) {
1551                         iscsi_data_digest_init(ctask->conn->dd_data, tcp_ctask);
1552                         dtask->digest = 0;
1553                 }
1554
1555                 tcp_ctask->xmstate &= ~XMSTATE_UNS_INIT;
1556                 iscsi_set_padding(tcp_ctask, ctask->data_count);
1557         }
1558
1559         rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, ctask->data_count);
1560         if (rc) {
1561                 tcp_ctask->xmstate &= ~XMSTATE_UNS_DATA;
1562                 tcp_ctask->xmstate |= XMSTATE_UNS_HDR;
1563                 return rc;
1564         }
1565
1566         debug_scsi("uns dout [itt 0x%x dlen %d sent %d]\n",
1567                    ctask->itt, ctask->unsol_count, tcp_ctask->sent);
1568         return 0;
1569 }
1570
1571 static int
1572 iscsi_send_unsol_pdu(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1573 {
1574         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1575         int rc;
1576
1577         if (tcp_ctask->xmstate & XMSTATE_UNS_HDR) {
1578                 BUG_ON(!ctask->unsol_count);
1579                 tcp_ctask->xmstate &= ~XMSTATE_UNS_HDR;
1580 send_hdr:
1581                 rc = iscsi_send_unsol_hdr(conn, ctask);
1582                 if (rc)
1583                         return rc;
1584         }
1585
1586         if (tcp_ctask->xmstate & XMSTATE_UNS_DATA) {
1587                 struct iscsi_data_task *dtask = &tcp_ctask->unsol_dtask;
1588                 int start = tcp_ctask->sent;
1589
1590                 rc = iscsi_send_data(ctask, &tcp_ctask->sendbuf, &tcp_ctask->sg,
1591                                      &tcp_ctask->sent, &ctask->data_count,
1592                                      &dtask->digestbuf, &dtask->digest);
1593                 ctask->unsol_count -= tcp_ctask->sent - start;
1594                 if (rc)
1595                         return rc;
1596                 tcp_ctask->xmstate &= ~XMSTATE_UNS_DATA;
1597                 /*
1598                  * Done with the Data-Out. Next, check if we need
1599                  * to send another unsolicited Data-Out.
1600                  */
1601                 if (ctask->unsol_count) {
1602                         debug_scsi("sending more uns\n");
1603                         tcp_ctask->xmstate |= XMSTATE_UNS_INIT;
1604                         goto send_hdr;
1605                 }
1606         }
1607         return 0;
1608 }
1609
1610 static int iscsi_send_sol_pdu(struct iscsi_conn *conn,
1611                               struct iscsi_cmd_task *ctask)
1612 {
1613         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1614         struct iscsi_session *session = conn->session;
1615         struct iscsi_r2t_info *r2t;
1616         struct iscsi_data_task *dtask;
1617         int left, rc;
1618
1619         if (tcp_ctask->xmstate & XMSTATE_SOL_HDR) {
1620                 tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR;
1621                 tcp_ctask->xmstate |= XMSTATE_SOL_DATA;
1622                 if (!tcp_ctask->r2t)
1623                         __kfifo_get(tcp_ctask->r2tqueue, (void*)&tcp_ctask->r2t,
1624                                     sizeof(void*));
1625 send_hdr:
1626                 r2t = tcp_ctask->r2t;
1627                 dtask = &r2t->dtask;
1628
1629                 if (conn->hdrdgst_en)
1630                         iscsi_hdr_digest(conn, &r2t->headbuf,
1631                                         (u8*)dtask->hdrext);
1632
1633                 if (conn->datadgst_en) {
1634                         iscsi_data_digest_init(conn->dd_data, tcp_ctask);
1635                         dtask->digest = 0;
1636                 }
1637
1638                 rc = iscsi_sendhdr(conn, &r2t->headbuf, r2t->data_count);
1639                 if (rc) {
1640                         tcp_ctask->xmstate &= ~XMSTATE_SOL_DATA;
1641                         tcp_ctask->xmstate |= XMSTATE_SOL_HDR;
1642                         return rc;
1643                 }
1644
1645                 iscsi_set_padding(tcp_ctask, r2t->data_count);
1646                 debug_scsi("sol dout [dsn %d itt 0x%x dlen %d sent %d]\n",
1647                         r2t->solicit_datasn - 1, ctask->itt, r2t->data_count,
1648                         r2t->sent);
1649         }
1650
1651         if (tcp_ctask->xmstate & XMSTATE_SOL_DATA) {
1652                 r2t = tcp_ctask->r2t;
1653                 dtask = &r2t->dtask;
1654
1655                 rc = iscsi_send_data(ctask, &r2t->sendbuf, &r2t->sg,
1656                                      &r2t->sent, &r2t->data_count,
1657                                      &dtask->digestbuf, &dtask->digest);
1658                 if (rc)
1659                         return rc;
1660                 tcp_ctask->xmstate &= ~XMSTATE_SOL_DATA;
1661
1662                 /*
1663                  * Done with this Data-Out. Next, check if we have
1664                  * to send another Data-Out for this R2T.
1665                  */
1666                 BUG_ON(r2t->data_length - r2t->sent < 0);
1667                 left = r2t->data_length - r2t->sent;
1668                 if (left) {
1669                         iscsi_solicit_data_cont(conn, ctask, r2t, left);
1670                         tcp_ctask->xmstate |= XMSTATE_SOL_DATA;
1671                         tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR;
1672                         goto send_hdr;
1673                 }
1674
1675                 /*
1676                  * Done with this R2T. Check if there are more
1677                  * outstanding R2Ts ready to be processed.
1678                  */
1679                 spin_lock_bh(&session->lock);
1680                 tcp_ctask->r2t = NULL;
1681                 __kfifo_put(tcp_ctask->r2tpool.queue, (void*)&r2t,
1682                             sizeof(void*));
1683                 if (__kfifo_get(tcp_ctask->r2tqueue, (void*)&r2t,
1684                                 sizeof(void*))) {
1685                         tcp_ctask->r2t = r2t;
1686                         tcp_ctask->xmstate |= XMSTATE_SOL_DATA;
1687                         tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR;
1688                         spin_unlock_bh(&session->lock);
1689                         goto send_hdr;
1690                 }
1691                 spin_unlock_bh(&session->lock);
1692         }
1693         return 0;
1694 }
1695
1696 static int
1697 iscsi_tcp_ctask_xmit(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1698 {
1699         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1700         int rc = 0;
1701
1702         debug_scsi("ctask deq [cid %d xmstate %x itt 0x%x]\n",
1703                 conn->id, tcp_ctask->xmstate, ctask->itt);
1704
1705         /*
1706          * serialize with TMF AbortTask
1707          */
1708         if (ctask->mtask)
1709                 return rc;
1710
1711         if (tcp_ctask->xmstate & XMSTATE_R_HDR)
1712                 return iscsi_send_read_hdr(conn, tcp_ctask);
1713
1714         if (tcp_ctask->xmstate & XMSTATE_W_HDR) {
1715                 rc = iscsi_send_write_hdr(conn, ctask);
1716                 if (rc)
1717                         return rc;
1718         }
1719
1720         if (tcp_ctask->xmstate & XMSTATE_IMM_DATA) {
1721                 rc = iscsi_send_data(ctask, &tcp_ctask->sendbuf, &tcp_ctask->sg,
1722                                      &tcp_ctask->sent, &ctask->imm_count,
1723                                      &tcp_ctask->immbuf, &tcp_ctask->immdigest);
1724                 if (rc)
1725                         return rc;
1726                 tcp_ctask->xmstate &= ~XMSTATE_IMM_DATA;
1727         }
1728
1729         rc = iscsi_send_unsol_pdu(conn, ctask);
1730         if (rc)
1731                 return rc;
1732
1733         rc = iscsi_send_sol_pdu(conn, ctask);
1734         if (rc)
1735                 return rc;
1736
1737         return rc;
1738 }
1739
1740 static struct iscsi_cls_conn *
1741 iscsi_tcp_conn_create(struct iscsi_cls_session *cls_session, uint32_t conn_idx)
1742 {
1743         struct iscsi_conn *conn;
1744         struct iscsi_cls_conn *cls_conn;
1745         struct iscsi_tcp_conn *tcp_conn;
1746
1747         cls_conn = iscsi_conn_setup(cls_session, conn_idx);
1748         if (!cls_conn)
1749                 return NULL;
1750         conn = cls_conn->dd_data;
1751         /*
1752          * due to strange issues with iser these are not set
1753          * in iscsi_conn_setup
1754          */
1755         conn->max_recv_dlength = DEFAULT_MAX_RECV_DATA_SEGMENT_LENGTH;
1756
1757         tcp_conn = kzalloc(sizeof(*tcp_conn), GFP_KERNEL);
1758         if (!tcp_conn)
1759                 goto tcp_conn_alloc_fail;
1760
1761         conn->dd_data = tcp_conn;
1762         tcp_conn->iscsi_conn = conn;
1763         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
1764         /* initial operational parameters */
1765         tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
1766
1767         return cls_conn;
1768
1769 tcp_conn_alloc_fail:
1770         iscsi_conn_teardown(cls_conn);
1771         return NULL;
1772 }
1773
1774 static void
1775 iscsi_tcp_release_conn(struct iscsi_conn *conn)
1776 {
1777         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1778
1779         if (!tcp_conn->sock)
1780                 return;
1781
1782         sock_hold(tcp_conn->sock->sk);
1783         iscsi_conn_restore_callbacks(tcp_conn);
1784         sock_put(tcp_conn->sock->sk);
1785
1786         sock_release(tcp_conn->sock);
1787         tcp_conn->sock = NULL;
1788         conn->recv_lock = NULL;
1789 }
1790
1791 static void
1792 iscsi_tcp_conn_destroy(struct iscsi_cls_conn *cls_conn)
1793 {
1794         struct iscsi_conn *conn = cls_conn->dd_data;
1795         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1796         int digest = 0;
1797
1798         if (conn->hdrdgst_en || conn->datadgst_en)
1799                 digest = 1;
1800
1801         iscsi_tcp_release_conn(conn);
1802         iscsi_conn_teardown(cls_conn);
1803
1804         /* now free tcp_conn */
1805         if (digest) {
1806                 if (tcp_conn->tx_tfm)
1807                         crypto_free_tfm(tcp_conn->tx_tfm);
1808                 if (tcp_conn->rx_tfm)
1809                         crypto_free_tfm(tcp_conn->rx_tfm);
1810                 if (tcp_conn->data_tx_tfm)
1811                         crypto_free_tfm(tcp_conn->data_tx_tfm);
1812                 if (tcp_conn->data_rx_tfm)
1813                         crypto_free_tfm(tcp_conn->data_rx_tfm);
1814         }
1815
1816         kfree(tcp_conn);
1817 }
1818
1819 static void
1820 iscsi_tcp_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
1821 {
1822         struct iscsi_conn *conn = cls_conn->dd_data;
1823
1824         iscsi_conn_stop(cls_conn, flag);
1825         iscsi_tcp_release_conn(conn);
1826 }
1827
1828 static int
1829 iscsi_tcp_conn_bind(struct iscsi_cls_session *cls_session,
1830                     struct iscsi_cls_conn *cls_conn, uint64_t transport_eph,
1831                     int is_leading)
1832 {
1833         struct iscsi_conn *conn = cls_conn->dd_data;
1834         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1835         struct sock *sk;
1836         struct socket *sock;
1837         int err;
1838
1839         /* lookup for existing socket */
1840         sock = sockfd_lookup((int)transport_eph, &err);
1841         if (!sock) {
1842                 printk(KERN_ERR "iscsi_tcp: sockfd_lookup failed %d\n", err);
1843                 return -EEXIST;
1844         }
1845
1846         err = iscsi_conn_bind(cls_session, cls_conn, is_leading);
1847         if (err)
1848                 return err;
1849
1850         /* bind iSCSI connection and socket */
1851         tcp_conn->sock = sock;
1852
1853         /* setup Socket parameters */
1854         sk = sock->sk;
1855         sk->sk_reuse = 1;
1856         sk->sk_sndtimeo = 15 * HZ; /* FIXME: make it configurable */
1857         sk->sk_allocation = GFP_ATOMIC;
1858
1859         /* FIXME: disable Nagle's algorithm */
1860
1861         /*
1862          * Intercept TCP callbacks for sendfile like receive
1863          * processing.
1864          */
1865         conn->recv_lock = &sk->sk_callback_lock;
1866         iscsi_conn_set_callbacks(conn);
1867         tcp_conn->sendpage = tcp_conn->sock->ops->sendpage;
1868         /*
1869          * set receive state machine into initial state
1870          */
1871         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
1872
1873         return 0;
1874 }
1875
1876 /* called with host lock */
1877 static void
1878 iscsi_tcp_mgmt_init(struct iscsi_conn *conn, struct iscsi_mgmt_task *mtask,
1879                     char *data, uint32_t data_size)
1880 {
1881         struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
1882
1883         iscsi_buf_init_iov(&tcp_mtask->headbuf, (char*)mtask->hdr,
1884                            sizeof(struct iscsi_hdr));
1885         tcp_mtask->xmstate = XMSTATE_IMM_HDR;
1886         tcp_mtask->sent = 0;
1887
1888         if (mtask->data_count)
1889                 iscsi_buf_init_iov(&tcp_mtask->sendbuf, (char*)mtask->data,
1890                                     mtask->data_count);
1891 }
1892
1893 static int
1894 iscsi_r2tpool_alloc(struct iscsi_session *session)
1895 {
1896         int i;
1897         int cmd_i;
1898
1899         /*
1900          * initialize per-task: R2T pool and xmit queue
1901          */
1902         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
1903                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
1904                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1905
1906                 /*
1907                  * pre-allocated x4 as much r2ts to handle race when
1908                  * target acks DataOut faster than we data_xmit() queues
1909                  * could replenish r2tqueue.
1910                  */
1911
1912                 /* R2T pool */
1913                 if (iscsi_pool_init(&tcp_ctask->r2tpool, session->max_r2t * 4,
1914                                     (void***)&tcp_ctask->r2ts,
1915                                     sizeof(struct iscsi_r2t_info))) {
1916                         goto r2t_alloc_fail;
1917                 }
1918
1919                 /* R2T xmit queue */
1920                 tcp_ctask->r2tqueue = kfifo_alloc(
1921                       session->max_r2t * 4 * sizeof(void*), GFP_KERNEL, NULL);
1922                 if (tcp_ctask->r2tqueue == ERR_PTR(-ENOMEM)) {
1923                         iscsi_pool_free(&tcp_ctask->r2tpool,
1924                                         (void**)tcp_ctask->r2ts);
1925                         goto r2t_alloc_fail;
1926                 }
1927         }
1928
1929         return 0;
1930
1931 r2t_alloc_fail:
1932         for (i = 0; i < cmd_i; i++) {
1933                 struct iscsi_cmd_task *ctask = session->cmds[i];
1934                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1935
1936                 kfifo_free(tcp_ctask->r2tqueue);
1937                 iscsi_pool_free(&tcp_ctask->r2tpool,
1938                                 (void**)tcp_ctask->r2ts);
1939         }
1940         return -ENOMEM;
1941 }
1942
1943 static void
1944 iscsi_r2tpool_free(struct iscsi_session *session)
1945 {
1946         int i;
1947
1948         for (i = 0; i < session->cmds_max; i++) {
1949                 struct iscsi_cmd_task *ctask = session->cmds[i];
1950                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1951
1952                 kfifo_free(tcp_ctask->r2tqueue);
1953                 iscsi_pool_free(&tcp_ctask->r2tpool,
1954                                 (void**)tcp_ctask->r2ts);
1955         }
1956 }
1957
1958 static int
1959 iscsi_conn_set_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param,
1960                      char *buf, int buflen)
1961 {
1962         struct iscsi_conn *conn = cls_conn->dd_data;
1963         struct iscsi_session *session = conn->session;
1964         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1965         int value;
1966
1967         switch(param) {
1968         case ISCSI_PARAM_HDRDGST_EN:
1969                 iscsi_set_param(cls_conn, param, buf, buflen);
1970                 tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
1971                 if (conn->hdrdgst_en) {
1972                         tcp_conn->hdr_size += sizeof(__u32);
1973                         if (!tcp_conn->tx_tfm)
1974                                 tcp_conn->tx_tfm = crypto_alloc_tfm("crc32c",
1975                                                                     0);
1976                         if (!tcp_conn->tx_tfm)
1977                                 return -ENOMEM;
1978                         if (!tcp_conn->rx_tfm)
1979                                 tcp_conn->rx_tfm = crypto_alloc_tfm("crc32c",
1980                                                                     0);
1981                         if (!tcp_conn->rx_tfm) {
1982                                 crypto_free_tfm(tcp_conn->tx_tfm);
1983                                 return -ENOMEM;
1984                         }
1985                 } else {
1986                         if (tcp_conn->tx_tfm)
1987                                 crypto_free_tfm(tcp_conn->tx_tfm);
1988                         if (tcp_conn->rx_tfm)
1989                                 crypto_free_tfm(tcp_conn->rx_tfm);
1990                 }
1991                 break;
1992         case ISCSI_PARAM_DATADGST_EN:
1993                 iscsi_set_param(cls_conn, param, buf, buflen);
1994                 if (conn->datadgst_en) {
1995                         if (!tcp_conn->data_tx_tfm)
1996                                 tcp_conn->data_tx_tfm =
1997                                     crypto_alloc_tfm("crc32c", 0);
1998                         if (!tcp_conn->data_tx_tfm)
1999                                 return -ENOMEM;
2000                         if (!tcp_conn->data_rx_tfm)
2001                                 tcp_conn->data_rx_tfm =
2002                                     crypto_alloc_tfm("crc32c", 0);
2003                         if (!tcp_conn->data_rx_tfm) {
2004                                 crypto_free_tfm(tcp_conn->data_tx_tfm);
2005                                 return -ENOMEM;
2006                         }
2007                 } else {
2008                         if (tcp_conn->data_tx_tfm)
2009                                 crypto_free_tfm(tcp_conn->data_tx_tfm);
2010                         if (tcp_conn->data_rx_tfm)
2011                                 crypto_free_tfm(tcp_conn->data_rx_tfm);
2012                 }
2013                 tcp_conn->sendpage = conn->datadgst_en ?
2014                         sock_no_sendpage : tcp_conn->sock->ops->sendpage;
2015                 break;
2016         case ISCSI_PARAM_MAX_R2T:
2017                 sscanf(buf, "%d", &value);
2018                 if (session->max_r2t == roundup_pow_of_two(value))
2019                         break;
2020                 iscsi_r2tpool_free(session);
2021                 iscsi_set_param(cls_conn, param, buf, buflen);
2022                 if (session->max_r2t & (session->max_r2t - 1))
2023                         session->max_r2t = roundup_pow_of_two(session->max_r2t);
2024                 if (iscsi_r2tpool_alloc(session))
2025                         return -ENOMEM;
2026                 break;
2027         default:
2028                 return iscsi_set_param(cls_conn, param, buf, buflen);
2029         }
2030
2031         return 0;
2032 }
2033
2034 static int
2035 iscsi_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn,
2036                          enum iscsi_param param, char *buf)
2037 {
2038         struct iscsi_conn *conn = cls_conn->dd_data;
2039         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2040         struct inet_sock *inet;
2041         struct ipv6_pinfo *np;
2042         struct sock *sk;
2043         int len;
2044
2045         switch(param) {
2046         case ISCSI_PARAM_CONN_PORT:
2047                 mutex_lock(&conn->xmitmutex);
2048                 if (!tcp_conn->sock) {
2049                         mutex_unlock(&conn->xmitmutex);
2050                         return -EINVAL;
2051                 }
2052
2053                 inet = inet_sk(tcp_conn->sock->sk);
2054                 len = sprintf(buf, "%hu\n", be16_to_cpu(inet->dport));
2055                 mutex_unlock(&conn->xmitmutex);
2056                 break;
2057         case ISCSI_PARAM_CONN_ADDRESS:
2058                 mutex_lock(&conn->xmitmutex);
2059                 if (!tcp_conn->sock) {
2060                         mutex_unlock(&conn->xmitmutex);
2061                         return -EINVAL;
2062                 }
2063
2064                 sk = tcp_conn->sock->sk;
2065                 if (sk->sk_family == PF_INET) {
2066                         inet = inet_sk(sk);
2067                         len = sprintf(buf, "%u.%u.%u.%u\n",
2068                                       NIPQUAD(inet->daddr));
2069                 } else {
2070                         np = inet6_sk(sk);
2071                         len = sprintf(buf,
2072                                 "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n",
2073                                 NIP6(np->daddr));
2074                 }
2075                 mutex_unlock(&conn->xmitmutex);
2076                 break;
2077         default:
2078                 return iscsi_conn_get_param(cls_conn, param, buf);
2079         }
2080
2081         return len;
2082 }
2083
2084 static void
2085 iscsi_conn_get_stats(struct iscsi_cls_conn *cls_conn, struct iscsi_stats *stats)
2086 {
2087         struct iscsi_conn *conn = cls_conn->dd_data;
2088         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2089
2090         stats->txdata_octets = conn->txdata_octets;
2091         stats->rxdata_octets = conn->rxdata_octets;
2092         stats->scsicmd_pdus = conn->scsicmd_pdus_cnt;
2093         stats->dataout_pdus = conn->dataout_pdus_cnt;
2094         stats->scsirsp_pdus = conn->scsirsp_pdus_cnt;
2095         stats->datain_pdus = conn->datain_pdus_cnt;
2096         stats->r2t_pdus = conn->r2t_pdus_cnt;
2097         stats->tmfcmd_pdus = conn->tmfcmd_pdus_cnt;
2098         stats->tmfrsp_pdus = conn->tmfrsp_pdus_cnt;
2099         stats->custom_length = 3;
2100         strcpy(stats->custom[0].desc, "tx_sendpage_failures");
2101         stats->custom[0].value = tcp_conn->sendpage_failures_cnt;
2102         strcpy(stats->custom[1].desc, "rx_discontiguous_hdr");
2103         stats->custom[1].value = tcp_conn->discontiguous_hdr_cnt;
2104         strcpy(stats->custom[2].desc, "eh_abort_cnt");
2105         stats->custom[2].value = conn->eh_abort_cnt;
2106 }
2107
2108 static struct iscsi_cls_session *
2109 iscsi_tcp_session_create(struct iscsi_transport *iscsit,
2110                          struct scsi_transport_template *scsit,
2111                          uint32_t initial_cmdsn, uint32_t *hostno)
2112 {
2113         struct iscsi_cls_session *cls_session;
2114         struct iscsi_session *session;
2115         uint32_t hn;
2116         int cmd_i;
2117
2118         cls_session = iscsi_session_setup(iscsit, scsit,
2119                                          sizeof(struct iscsi_tcp_cmd_task),
2120                                          sizeof(struct iscsi_tcp_mgmt_task),
2121                                          initial_cmdsn, &hn);
2122         if (!cls_session)
2123                 return NULL;
2124         *hostno = hn;
2125
2126         session = class_to_transport_session(cls_session);
2127         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2128                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
2129                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
2130
2131                 ctask->hdr = &tcp_ctask->hdr;
2132         }
2133
2134         for (cmd_i = 0; cmd_i < session->mgmtpool_max; cmd_i++) {
2135                 struct iscsi_mgmt_task *mtask = session->mgmt_cmds[cmd_i];
2136                 struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
2137
2138                 mtask->hdr = &tcp_mtask->hdr;
2139         }
2140
2141         if (iscsi_r2tpool_alloc(class_to_transport_session(cls_session)))
2142                 goto r2tpool_alloc_fail;
2143
2144         return cls_session;
2145
2146 r2tpool_alloc_fail:
2147         iscsi_session_teardown(cls_session);
2148         return NULL;
2149 }
2150
2151 static void iscsi_tcp_session_destroy(struct iscsi_cls_session *cls_session)
2152 {
2153         iscsi_r2tpool_free(class_to_transport_session(cls_session));
2154         iscsi_session_teardown(cls_session);
2155 }
2156
2157 static struct scsi_host_template iscsi_sht = {
2158         .name                   = "iSCSI Initiator over TCP/IP",
2159         .queuecommand           = iscsi_queuecommand,
2160         .change_queue_depth     = iscsi_change_queue_depth,
2161         .can_queue              = ISCSI_XMIT_CMDS_MAX - 1,
2162         .sg_tablesize           = ISCSI_SG_TABLESIZE,
2163         .cmd_per_lun            = ISCSI_DEF_CMD_PER_LUN,
2164         .eh_abort_handler       = iscsi_eh_abort,
2165         .eh_host_reset_handler  = iscsi_eh_host_reset,
2166         .use_clustering         = DISABLE_CLUSTERING,
2167         .proc_name              = "iscsi_tcp",
2168         .this_id                = -1,
2169 };
2170
2171 static struct iscsi_transport iscsi_tcp_transport = {
2172         .owner                  = THIS_MODULE,
2173         .name                   = "tcp",
2174         .caps                   = CAP_RECOVERY_L0 | CAP_MULTI_R2T | CAP_HDRDGST
2175                                   | CAP_DATADGST,
2176         .param_mask             = ISCSI_MAX_RECV_DLENGTH |
2177                                   ISCSI_MAX_XMIT_DLENGTH |
2178                                   ISCSI_HDRDGST_EN |
2179                                   ISCSI_DATADGST_EN |
2180                                   ISCSI_INITIAL_R2T_EN |
2181                                   ISCSI_MAX_R2T |
2182                                   ISCSI_IMM_DATA_EN |
2183                                   ISCSI_FIRST_BURST |
2184                                   ISCSI_MAX_BURST |
2185                                   ISCSI_PDU_INORDER_EN |
2186                                   ISCSI_DATASEQ_INORDER_EN |
2187                                   ISCSI_ERL |
2188                                   ISCSI_CONN_PORT |
2189                                   ISCSI_CONN_ADDRESS |
2190                                   ISCSI_EXP_STATSN |
2191                                   ISCSI_PERSISTENT_PORT |
2192                                   ISCSI_PERSISTENT_ADDRESS |
2193                                   ISCSI_TARGET_NAME |
2194                                   ISCSI_TPGT,
2195         .host_template          = &iscsi_sht,
2196         .conndata_size          = sizeof(struct iscsi_conn),
2197         .max_conn               = 1,
2198         .max_cmd_len            = ISCSI_TCP_MAX_CMD_LEN,
2199         /* session management */
2200         .create_session         = iscsi_tcp_session_create,
2201         .destroy_session        = iscsi_tcp_session_destroy,
2202         /* connection management */
2203         .create_conn            = iscsi_tcp_conn_create,
2204         .bind_conn              = iscsi_tcp_conn_bind,
2205         .destroy_conn           = iscsi_tcp_conn_destroy,
2206         .set_param              = iscsi_conn_set_param,
2207         .get_conn_param         = iscsi_tcp_conn_get_param,
2208         .get_session_param      = iscsi_session_get_param,
2209         .start_conn             = iscsi_conn_start,
2210         .stop_conn              = iscsi_tcp_conn_stop,
2211         /* IO */
2212         .send_pdu               = iscsi_conn_send_pdu,
2213         .get_stats              = iscsi_conn_get_stats,
2214         .init_cmd_task          = iscsi_tcp_cmd_init,
2215         .init_mgmt_task         = iscsi_tcp_mgmt_init,
2216         .xmit_cmd_task          = iscsi_tcp_ctask_xmit,
2217         .xmit_mgmt_task         = iscsi_tcp_mtask_xmit,
2218         .cleanup_cmd_task       = iscsi_tcp_cleanup_ctask,
2219         /* recovery */
2220         .session_recovery_timedout = iscsi_session_recovery_timedout,
2221 };
2222
2223 static int __init
2224 iscsi_tcp_init(void)
2225 {
2226         if (iscsi_max_lun < 1) {
2227                 printk(KERN_ERR "iscsi_tcp: Invalid max_lun value of %u\n",
2228                        iscsi_max_lun);
2229                 return -EINVAL;
2230         }
2231         iscsi_tcp_transport.max_lun = iscsi_max_lun;
2232
2233         if (!iscsi_register_transport(&iscsi_tcp_transport))
2234                 return -ENODEV;
2235
2236         return 0;
2237 }
2238
2239 static void __exit
2240 iscsi_tcp_exit(void)
2241 {
2242         iscsi_unregister_transport(&iscsi_tcp_transport);
2243 }
2244
2245 module_init(iscsi_tcp_init);
2246 module_exit(iscsi_tcp_exit);