1 /*
2  * Copyright (c) 2007-2011 Atheros Communications Inc.
3  * Copyright (c) 2011-2012 Qualcomm Atheros, Inc.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include "core.h"
19 #include "hif.h"
20 #include "debug.h"
21 #include "hif-ops.h"
22 #include <asm/unaligned.h>
23 
24 #define CALC_TXRX_PADDED_LEN(dev, len)  (__ALIGN_MASK((len), (dev)->block_mask))
25 
26 static void ath6kl_htc_mbox_cleanup(struct htc_target *target);
27 static void ath6kl_htc_mbox_stop(struct htc_target *target);
28 static int ath6kl_htc_mbox_add_rxbuf_multiple(struct htc_target *target,
29 					      struct list_head *pkt_queue);
30 static void ath6kl_htc_set_credit_dist(struct htc_target *target,
31 				       struct ath6kl_htc_credit_info *cred_info,
32 				       u16 svc_pri_order[], int len);
33 
34 /* threshold to re-enable Tx bundling for an AC*/
35 #define TX_RESUME_BUNDLE_THRESHOLD	1500
36 
37 /* Functions for Tx credit handling */
38 static void ath6kl_credit_deposit(struct ath6kl_htc_credit_info *cred_info,
39 				  struct htc_endpoint_credit_dist *ep_dist,
40 				  int credits)
41 {
42 	ath6kl_dbg(ATH6KL_DBG_CREDIT, "credit deposit ep %d credits %d\n",
43 		   ep_dist->endpoint, credits);
44 
45 	ep_dist->credits += credits;
46 	ep_dist->cred_assngd += credits;
47 	cred_info->cur_free_credits -= credits;
48 }
49 
50 static void ath6kl_credit_init(struct ath6kl_htc_credit_info *cred_info,
51 			       struct list_head *ep_list,
52 			       int tot_credits)
53 {
54 	struct htc_endpoint_credit_dist *cur_ep_dist;
55 	int count;
56 
57 	ath6kl_dbg(ATH6KL_DBG_CREDIT, "credit init total %d\n", tot_credits);
58 
59 	cred_info->cur_free_credits = tot_credits;
60 	cred_info->total_avail_credits = tot_credits;
61 
62 	list_for_each_entry(cur_ep_dist, ep_list, list) {
63 		if (cur_ep_dist->endpoint == ENDPOINT_0)
64 			continue;
65 
66 		cur_ep_dist->cred_min = cur_ep_dist->cred_per_msg;
67 
68 		if (tot_credits > 4) {
69 			if ((cur_ep_dist->svc_id == WMI_DATA_BK_SVC) ||
70 			    (cur_ep_dist->svc_id == WMI_DATA_BE_SVC)) {
71 				ath6kl_credit_deposit(cred_info,
72 						      cur_ep_dist,
73 						      cur_ep_dist->cred_min);
74 				cur_ep_dist->dist_flags |= HTC_EP_ACTIVE;
75 			}
76 		}
77 
78 		if (cur_ep_dist->svc_id == WMI_CONTROL_SVC) {
79 			ath6kl_credit_deposit(cred_info, cur_ep_dist,
80 					      cur_ep_dist->cred_min);
81 			/*
82 			 * Control service is always marked active, it
83 			 * never goes inactive EVER.
84 			 */
85 			cur_ep_dist->dist_flags |= HTC_EP_ACTIVE;
86 		}
87 
88 		/*
89 		 * Streams have to be created (explicit | implicit) for all
90 		 * kinds of traffic. BE endpoints are also inactive in the
91 		 * beginning. When BE traffic starts it creates implicit
92 		 * streams that redistributes credits.
93 		 *
94 		 * Note: all other endpoints have minimums set but are
95 		 * initially given NO credits. credits will be distributed
96 		 * as traffic activity demands
97 		 */
98 	}
99 
100 	/*
101 	 * For ath6kl_credit_seek function,
102 	 * it use list_for_each_entry_reverse to walk around the whole ep list.
103 	 * Therefore assign this lowestpri_ep_dist after walk around the ep_list
104 	 */
105 	cred_info->lowestpri_ep_dist = cur_ep_dist->list;
106 
107 	WARN_ON(cred_info->cur_free_credits <= 0);
108 
109 	list_for_each_entry(cur_ep_dist, ep_list, list) {
110 		if (cur_ep_dist->endpoint == ENDPOINT_0)
111 			continue;
112 
113 		if (cur_ep_dist->svc_id == WMI_CONTROL_SVC)
114 			cur_ep_dist->cred_norm = cur_ep_dist->cred_per_msg;
115 		else {
116 			/*
117 			 * For the remaining data endpoints, we assume that
118 			 * each cred_per_msg are the same. We use a simple
119 			 * calculation here, we take the remaining credits
120 			 * and determine how many max messages this can
121 			 * cover and then set each endpoint's normal value
122 			 * equal to 3/4 this amount.
123 			 */
124 			count = (cred_info->cur_free_credits /
125 				 cur_ep_dist->cred_per_msg)
126 				* cur_ep_dist->cred_per_msg;
127 			count = (count * 3) >> 2;
128 			count = max(count, cur_ep_dist->cred_per_msg);
129 			cur_ep_dist->cred_norm = count;
130 
131 		}
132 
133 		ath6kl_dbg(ATH6KL_DBG_CREDIT,
134 			   "credit ep %d svc_id %d credits %d per_msg %d norm %d min %d\n",
135 			   cur_ep_dist->endpoint,
136 			   cur_ep_dist->svc_id,
137 			   cur_ep_dist->credits,
138 			   cur_ep_dist->cred_per_msg,
139 			   cur_ep_dist->cred_norm,
140 			   cur_ep_dist->cred_min);
141 	}
142 }
143 
144 /* initialize and setup credit distribution */
145 static int ath6kl_htc_mbox_credit_setup(struct htc_target *htc_target,
146 			       struct ath6kl_htc_credit_info *cred_info)
147 {
148 	u16 servicepriority[5];
149 
150 	memset(cred_info, 0, sizeof(struct ath6kl_htc_credit_info));
151 
152 	servicepriority[0] = WMI_CONTROL_SVC;  /* highest */
153 	servicepriority[1] = WMI_DATA_VO_SVC;
154 	servicepriority[2] = WMI_DATA_VI_SVC;
155 	servicepriority[3] = WMI_DATA_BE_SVC;
156 	servicepriority[4] = WMI_DATA_BK_SVC; /* lowest */
157 
158 	/* set priority list */
159 	ath6kl_htc_set_credit_dist(htc_target, cred_info, servicepriority, 5);
160 
161 	return 0;
162 }
163 
164 /* reduce an ep's credits back to a set limit */
165 static void ath6kl_credit_reduce(struct ath6kl_htc_credit_info *cred_info,
166 				 struct htc_endpoint_credit_dist *ep_dist,
167 				 int limit)
168 {
169 	int credits;
170 
171 	ath6kl_dbg(ATH6KL_DBG_CREDIT, "credit reduce ep %d limit %d\n",
172 		   ep_dist->endpoint, limit);
173 
174 	ep_dist->cred_assngd = limit;
175 
176 	if (ep_dist->credits <= limit)
177 		return;
178 
179 	credits = ep_dist->credits - limit;
180 	ep_dist->credits -= credits;
181 	cred_info->cur_free_credits += credits;
182 }
183 
184 static void ath6kl_credit_update(struct ath6kl_htc_credit_info *cred_info,
185 				 struct list_head *epdist_list)
186 {
187 	struct htc_endpoint_credit_dist *cur_list;
188 
189 	list_for_each_entry(cur_list, epdist_list, list) {
190 		if (cur_list->endpoint == ENDPOINT_0)
191 			continue;
192 
193 		if (cur_list->cred_to_dist > 0) {
194 			cur_list->credits += cur_list->cred_to_dist;
195 			cur_list->cred_to_dist = 0;
196 
197 			if (cur_list->credits > cur_list->cred_assngd)
198 				ath6kl_credit_reduce(cred_info,
199 						     cur_list,
200 						     cur_list->cred_assngd);
201 
202 			if (cur_list->credits > cur_list->cred_norm)
203 				ath6kl_credit_reduce(cred_info, cur_list,
204 						     cur_list->cred_norm);
205 
206 			if (!(cur_list->dist_flags & HTC_EP_ACTIVE)) {
207 				if (cur_list->txq_depth == 0)
208 					ath6kl_credit_reduce(cred_info,
209 							     cur_list, 0);
210 			}
211 		}
212 	}
213 }
214 
215 /*
216  * HTC has an endpoint that needs credits, ep_dist is the endpoint in
217  * question.
218  */
219 static void ath6kl_credit_seek(struct ath6kl_htc_credit_info *cred_info,
220 				struct htc_endpoint_credit_dist *ep_dist)
221 {
222 	struct htc_endpoint_credit_dist *curdist_list;
223 	int credits = 0;
224 	int need;
225 
226 	if (ep_dist->svc_id == WMI_CONTROL_SVC)
227 		goto out;
228 
229 	if ((ep_dist->svc_id == WMI_DATA_VI_SVC) ||
230 	    (ep_dist->svc_id == WMI_DATA_VO_SVC))
231 		if ((ep_dist->cred_assngd >= ep_dist->cred_norm))
232 			goto out;
233 
234 	/*
235 	 * For all other services, we follow a simple algorithm of:
236 	 *
237 	 * 1. checking the free pool for credits
238 	 * 2. checking lower priority endpoints for credits to take
239 	 */
240 
241 	credits = min(cred_info->cur_free_credits, ep_dist->seek_cred);
242 
243 	if (credits >= ep_dist->seek_cred)
244 		goto out;
245 
246 	/*
247 	 * We don't have enough in the free pool, try taking away from
248 	 * lower priority services The rule for taking away credits:
249 	 *
250 	 *   1. Only take from lower priority endpoints
251 	 *   2. Only take what is allocated above the minimum (never
252 	 *      starve an endpoint completely)
253 	 *   3. Only take what you need.
254 	 */
255 
256 	list_for_each_entry_reverse(curdist_list,
257 				    &cred_info->lowestpri_ep_dist,
258 				    list) {
259 		if (curdist_list == ep_dist)
260 			break;
261 
262 		need = ep_dist->seek_cred - cred_info->cur_free_credits;
263 
264 		if ((curdist_list->cred_assngd - need) >=
265 		     curdist_list->cred_min) {
266 			/*
267 			 * The current one has been allocated more than
268 			 * it's minimum and it has enough credits assigned
269 			 * above it's minimum to fulfill our need try to
270 			 * take away just enough to fulfill our need.
271 			 */
272 			ath6kl_credit_reduce(cred_info, curdist_list,
273 					     curdist_list->cred_assngd - need);
274 
275 			if (cred_info->cur_free_credits >=
276 			    ep_dist->seek_cred)
277 				break;
278 		}
279 
280 		if (curdist_list->endpoint == ENDPOINT_0)
281 			break;
282 	}
283 
284 	credits = min(cred_info->cur_free_credits, ep_dist->seek_cred);
285 
286 out:
287 	/* did we find some credits? */
288 	if (credits)
289 		ath6kl_credit_deposit(cred_info, ep_dist, credits);
290 
291 	ep_dist->seek_cred = 0;
292 }
293 
294 /* redistribute credits based on activity change */
295 static void ath6kl_credit_redistribute(struct ath6kl_htc_credit_info *info,
296 				       struct list_head *ep_dist_list)
297 {
298 	struct htc_endpoint_credit_dist *curdist_list;
299 
300 	list_for_each_entry(curdist_list, ep_dist_list, list) {
301 		if (curdist_list->endpoint == ENDPOINT_0)
302 			continue;
303 
304 		if ((curdist_list->svc_id == WMI_DATA_BK_SVC)  ||
305 		    (curdist_list->svc_id == WMI_DATA_BE_SVC))
306 			curdist_list->dist_flags |= HTC_EP_ACTIVE;
307 
308 		if ((curdist_list->svc_id != WMI_CONTROL_SVC) &&
309 		    !(curdist_list->dist_flags & HTC_EP_ACTIVE)) {
310 			if (curdist_list->txq_depth == 0)
311 				ath6kl_credit_reduce(info, curdist_list, 0);
312 			else
313 				ath6kl_credit_reduce(info,
314 						     curdist_list,
315 						     curdist_list->cred_min);
316 		}
317 	}
318 }
319 
320 /*
321  *
322  * This function is invoked whenever endpoints require credit
323  * distributions. A lock is held while this function is invoked, this
324  * function shall NOT block. The ep_dist_list is a list of distribution
325  * structures in prioritized order as defined by the call to the
326  * htc_set_credit_dist() api.
327  */
328 static void ath6kl_credit_distribute(struct ath6kl_htc_credit_info *cred_info,
329 				     struct list_head *ep_dist_list,
330 			      enum htc_credit_dist_reason reason)
331 {
332 	switch (reason) {
333 	case HTC_CREDIT_DIST_SEND_COMPLETE:
334 		ath6kl_credit_update(cred_info, ep_dist_list);
335 		break;
336 	case HTC_CREDIT_DIST_ACTIVITY_CHANGE:
337 		ath6kl_credit_redistribute(cred_info, ep_dist_list);
338 		break;
339 	default:
340 		break;
341 	}
342 
343 	WARN_ON(cred_info->cur_free_credits > cred_info->total_avail_credits);
344 	WARN_ON(cred_info->cur_free_credits < 0);
345 }
346 
347 static void ath6kl_htc_tx_buf_align(u8 **buf, unsigned long len)
348 {
349 	u8 *align_addr;
350 
351 	if (!IS_ALIGNED((unsigned long) *buf, 4)) {
352 		align_addr = PTR_ALIGN(*buf - 4, 4);
353 		memmove(align_addr, *buf, len);
354 		*buf = align_addr;
355 	}
356 }
357 
358 static void ath6kl_htc_tx_prep_pkt(struct htc_packet *packet, u8 flags,
359 				   int ctrl0, int ctrl1)
360 {
361 	struct htc_frame_hdr *hdr;
362 
363 	packet->buf -= HTC_HDR_LENGTH;
364 	hdr =  (struct htc_frame_hdr *)packet->buf;
365 
366 	/* Endianess? */
367 	put_unaligned((u16)packet->act_len, &hdr->payld_len);
368 	hdr->flags = flags;
369 	hdr->eid = packet->endpoint;
370 	hdr->ctrl[0] = ctrl0;
371 	hdr->ctrl[1] = ctrl1;
372 }
373 
374 static void htc_reclaim_txctrl_buf(struct htc_target *target,
375 				   struct htc_packet *pkt)
376 {
377 	spin_lock_bh(&target->htc_lock);
378 	list_add_tail(&pkt->list, &target->free_ctrl_txbuf);
379 	spin_unlock_bh(&target->htc_lock);
380 }
381 
382 static struct htc_packet *htc_get_control_buf(struct htc_target *target,
383 					      bool tx)
384 {
385 	struct htc_packet *packet = NULL;
386 	struct list_head *buf_list;
387 
388 	buf_list = tx ? &target->free_ctrl_txbuf : &target->free_ctrl_rxbuf;
389 
390 	spin_lock_bh(&target->htc_lock);
391 
392 	if (list_empty(buf_list)) {
393 		spin_unlock_bh(&target->htc_lock);
394 		return NULL;
395 	}
396 
397 	packet = list_first_entry(buf_list, struct htc_packet, list);
398 	list_del(&packet->list);
399 	spin_unlock_bh(&target->htc_lock);
400 
401 	if (tx)
402 		packet->buf = packet->buf_start + HTC_HDR_LENGTH;
403 
404 	return packet;
405 }
406 
407 static void htc_tx_comp_update(struct htc_target *target,
408 			       struct htc_endpoint *endpoint,
409 			       struct htc_packet *packet)
410 {
411 	packet->completion = NULL;
412 	packet->buf += HTC_HDR_LENGTH;
413 
414 	if (!packet->status)
415 		return;
416 
417 	ath6kl_err("req failed (status:%d, ep:%d, len:%d creds:%d)\n",
418 		   packet->status, packet->endpoint, packet->act_len,
419 		   packet->info.tx.cred_used);
420 
421 	/* on failure to submit, reclaim credits for this packet */
422 	spin_lock_bh(&target->tx_lock);
423 	endpoint->cred_dist.cred_to_dist +=
424 				packet->info.tx.cred_used;
425 	endpoint->cred_dist.txq_depth = get_queue_depth(&endpoint->txq);
426 
427 	ath6kl_dbg(ATH6KL_DBG_HTC, "htc tx ctxt 0x%p dist 0x%p\n",
428 		   target->credit_info, &target->cred_dist_list);
429 
430 	ath6kl_credit_distribute(target->credit_info,
431 				 &target->cred_dist_list,
432 				 HTC_CREDIT_DIST_SEND_COMPLETE);
433 
434 	spin_unlock_bh(&target->tx_lock);
435 }
436 
437 static void htc_tx_complete(struct htc_endpoint *endpoint,
438 			    struct list_head *txq)
439 {
440 	if (list_empty(txq))
441 		return;
442 
443 	ath6kl_dbg(ATH6KL_DBG_HTC,
444 		   "htc tx complete ep %d pkts %d\n",
445 		   endpoint->eid, get_queue_depth(txq));
446 
447 	ath6kl_tx_complete(endpoint->target, txq);
448 }
449 
450 static void htc_tx_comp_handler(struct htc_target *target,
451 				struct htc_packet *packet)
452 {
453 	struct htc_endpoint *endpoint = &target->endpoint[packet->endpoint];
454 	struct list_head container;
455 
456 	ath6kl_dbg(ATH6KL_DBG_HTC, "htc tx complete seqno %d\n",
457 		   packet->info.tx.seqno);
458 
459 	htc_tx_comp_update(target, endpoint, packet);
460 	INIT_LIST_HEAD(&container);
461 	list_add_tail(&packet->list, &container);
462 	/* do completion */
463 	htc_tx_complete(endpoint, &container);
464 }
465 
466 static void htc_async_tx_scat_complete(struct htc_target *target,
467 				       struct hif_scatter_req *scat_req)
468 {
469 	struct htc_endpoint *endpoint;
470 	struct htc_packet *packet;
471 	struct list_head tx_compq;
472 	int i;
473 
474 	INIT_LIST_HEAD(&tx_compq);
475 
476 	ath6kl_dbg(ATH6KL_DBG_HTC,
477 		   "htc tx scat complete len %d entries %d\n",
478 		   scat_req->len, scat_req->scat_entries);
479 
480 	if (scat_req->status)
481 		ath6kl_err("send scatter req failed: %d\n", scat_req->status);
482 
483 	packet = scat_req->scat_list[0].packet;
484 	endpoint = &target->endpoint[packet->endpoint];
485 
486 	/* walk through the scatter list and process */
487 	for (i = 0; i < scat_req->scat_entries; i++) {
488 		packet = scat_req->scat_list[i].packet;
489 		if (!packet) {
490 			WARN_ON(1);
491 			return;
492 		}
493 
494 		packet->status = scat_req->status;
495 		htc_tx_comp_update(target, endpoint, packet);
496 		list_add_tail(&packet->list, &tx_compq);
497 	}
498 
499 	/* free scatter request */
500 	hif_scatter_req_add(target->dev->ar, scat_req);
501 
502 	/* complete all packets */
503 	htc_tx_complete(endpoint, &tx_compq);
504 }
505 
506 static int ath6kl_htc_tx_issue(struct htc_target *target,
507 			       struct htc_packet *packet)
508 {
509 	int status;
510 	bool sync = false;
511 	u32 padded_len, send_len;
512 
513 	if (!packet->completion)
514 		sync = true;
515 
516 	send_len = packet->act_len + HTC_HDR_LENGTH;
517 
518 	padded_len = CALC_TXRX_PADDED_LEN(target, send_len);
519 
520 	ath6kl_dbg(ATH6KL_DBG_HTC,
521 		   "htc tx issue len %d seqno %d padded_len %d mbox 0x%X %s\n",
522 		   send_len, packet->info.tx.seqno, padded_len,
523 		   target->dev->ar->mbox_info.htc_addr,
524 		   sync ? "sync" : "async");
525 
526 	if (sync) {
527 		status = hif_read_write_sync(target->dev->ar,
528 				target->dev->ar->mbox_info.htc_addr,
529 				 packet->buf, padded_len,
530 				 HIF_WR_SYNC_BLOCK_INC);
531 
532 		packet->status = status;
533 		packet->buf += HTC_HDR_LENGTH;
534 	} else
535 		status = hif_write_async(target->dev->ar,
536 				target->dev->ar->mbox_info.htc_addr,
537 				packet->buf, padded_len,
538 				HIF_WR_ASYNC_BLOCK_INC, packet);
539 
540 	return status;
541 }
542 
543 static int htc_check_credits(struct htc_target *target,
544 			     struct htc_endpoint *ep, u8 *flags,
545 			     enum htc_endpoint_id eid, unsigned int len,
546 			     int *req_cred)
547 {
548 
549 	*req_cred = (len > target->tgt_cred_sz) ?
550 		     DIV_ROUND_UP(len, target->tgt_cred_sz) : 1;
551 
552 	ath6kl_dbg(ATH6KL_DBG_CREDIT, "credit check need %d got %d\n",
553 		   *req_cred, ep->cred_dist.credits);
554 
555 	if (ep->cred_dist.credits < *req_cred) {
556 		if (eid == ENDPOINT_0)
557 			return -EINVAL;
558 
559 		/* Seek more credits */
560 		ep->cred_dist.seek_cred = *req_cred - ep->cred_dist.credits;
561 
562 		ath6kl_credit_seek(target->credit_info, &ep->cred_dist);
563 
564 		ep->cred_dist.seek_cred = 0;
565 
566 		if (ep->cred_dist.credits < *req_cred) {
567 			ath6kl_dbg(ATH6KL_DBG_CREDIT,
568 				   "credit not found for ep %d\n",
569 				   eid);
570 			return -EINVAL;
571 		}
572 	}
573 
574 	ep->cred_dist.credits -= *req_cred;
575 	ep->ep_st.cred_cosumd += *req_cred;
576 
577 	 /* When we are getting low on credits, ask for more */
578 	if (ep->cred_dist.credits < ep->cred_dist.cred_per_msg) {
579 		ep->cred_dist.seek_cred =
580 		ep->cred_dist.cred_per_msg - ep->cred_dist.credits;
581 
582 		ath6kl_credit_seek(target->credit_info, &ep->cred_dist);
583 
584 		/* see if we were successful in getting more */
585 		if (ep->cred_dist.credits < ep->cred_dist.cred_per_msg) {
586 			/* tell the target we need credits ASAP! */
587 			*flags |= HTC_FLAGS_NEED_CREDIT_UPDATE;
588 			ep->ep_st.cred_low_indicate += 1;
589 			ath6kl_dbg(ATH6KL_DBG_CREDIT,
590 				   "credit we need credits asap\n");
591 		}
592 	}
593 
594 	return 0;
595 }
596 
597 static void ath6kl_htc_tx_pkts_get(struct htc_target *target,
598 				   struct htc_endpoint *endpoint,
599 				   struct list_head *queue)
600 {
601 	int req_cred;
602 	u8 flags;
603 	struct htc_packet *packet;
604 	unsigned int len;
605 
606 	while (true) {
607 
608 		flags = 0;
609 
610 		if (list_empty(&endpoint->txq))
611 			break;
612 		packet = list_first_entry(&endpoint->txq, struct htc_packet,
613 					  list);
614 
615 		ath6kl_dbg(ATH6KL_DBG_HTC,
616 			   "htc tx got packet 0x%p queue depth %d\n",
617 			   packet, get_queue_depth(&endpoint->txq));
618 
619 		len = CALC_TXRX_PADDED_LEN(target,
620 					   packet->act_len + HTC_HDR_LENGTH);
621 
622 		if (htc_check_credits(target, endpoint, &flags,
623 				      packet->endpoint, len, &req_cred))
624 			break;
625 
626 		/* now we can fully move onto caller's queue */
627 		packet = list_first_entry(&endpoint->txq, struct htc_packet,
628 					  list);
629 		list_move_tail(&packet->list, queue);
630 
631 		/* save the number of credits this packet consumed */
632 		packet->info.tx.cred_used = req_cred;
633 
634 		/* all TX packets are handled asynchronously */
635 		packet->completion = htc_tx_comp_handler;
636 		packet->context = target;
637 		endpoint->ep_st.tx_issued += 1;
638 
639 		/* save send flags */
640 		packet->info.tx.flags = flags;
641 		packet->info.tx.seqno = endpoint->seqno;
642 		endpoint->seqno++;
643 	}
644 }
645 
646 /* See if the padded tx length falls on a credit boundary */
647 static int htc_get_credit_padding(unsigned int cred_sz, int *len,
648 				  struct htc_endpoint *ep)
649 {
650 	int rem_cred, cred_pad;
651 
652 	rem_cred = *len % cred_sz;
653 
654 	/* No padding needed */
655 	if  (!rem_cred)
656 		return 0;
657 
658 	if (!(ep->conn_flags & HTC_FLGS_TX_BNDL_PAD_EN))
659 		return -1;
660 
661 	/*
662 	 * The transfer consumes a "partial" credit, this
663 	 * packet cannot be bundled unless we add
664 	 * additional "dummy" padding (max 255 bytes) to
665 	 * consume the entire credit.
666 	 */
667 	cred_pad = *len < cred_sz ? (cred_sz - *len) : rem_cred;
668 
669 	if ((cred_pad > 0) && (cred_pad <= 255))
670 		*len += cred_pad;
671 	else
672 		/* The amount of padding is too large, send as non-bundled */
673 		return -1;
674 
675 	return cred_pad;
676 }
677 
678 static int ath6kl_htc_tx_setup_scat_list(struct htc_target *target,
679 					 struct htc_endpoint *endpoint,
680 					 struct hif_scatter_req *scat_req,
681 					 int n_scat,
682 					 struct list_head *queue)
683 {
684 	struct htc_packet *packet;
685 	int i, len, rem_scat, cred_pad;
686 	int status = 0;
687 	u8 flags;
688 
689 	rem_scat = target->max_tx_bndl_sz;
690 
691 	for (i = 0; i < n_scat; i++) {
692 		scat_req->scat_list[i].packet = NULL;
693 
694 		if (list_empty(queue))
695 			break;
696 
697 		packet = list_first_entry(queue, struct htc_packet, list);
698 		len = CALC_TXRX_PADDED_LEN(target,
699 					   packet->act_len + HTC_HDR_LENGTH);
700 
701 		cred_pad = htc_get_credit_padding(target->tgt_cred_sz,
702 						  &len, endpoint);
703 		if (cred_pad < 0 || rem_scat < len) {
704 			status = -ENOSPC;
705 			break;
706 		}
707 
708 		rem_scat -= len;
709 		/* now remove it from the queue */
710 		list_del(&packet->list);
711 
712 		scat_req->scat_list[i].packet = packet;
713 		/* prepare packet and flag message as part of a send bundle */
714 		flags = packet->info.tx.flags | HTC_FLAGS_SEND_BUNDLE;
715 		ath6kl_htc_tx_prep_pkt(packet, flags,
716 				       cred_pad, packet->info.tx.seqno);
717 		/* Make sure the buffer is 4-byte aligned */
718 		ath6kl_htc_tx_buf_align(&packet->buf,
719 					packet->act_len + HTC_HDR_LENGTH);
720 		scat_req->scat_list[i].buf = packet->buf;
721 		scat_req->scat_list[i].len = len;
722 
723 		scat_req->len += len;
724 		scat_req->scat_entries++;
725 		ath6kl_dbg(ATH6KL_DBG_HTC,
726 			   "htc tx adding (%d) pkt 0x%p seqno %d len %d remaining %d\n",
727 			   i, packet, packet->info.tx.seqno, len, rem_scat);
728 	}
729 
730 	/* Roll back scatter setup in case of any failure */
731 	if (scat_req->scat_entries < HTC_MIN_HTC_MSGS_TO_BUNDLE) {
732 		for (i = scat_req->scat_entries - 1; i >= 0; i--) {
733 			packet = scat_req->scat_list[i].packet;
734 			if (packet) {
735 				packet->buf += HTC_HDR_LENGTH;
736 				list_add(&packet->list, queue);
737 			}
738 		}
739 		return -EAGAIN;
740 	}
741 
742 	return status;
743 }
744 
745 /*
746  * Drain a queue and send as bundles this function may return without fully
747  * draining the queue when
748  *
749  *    1. scatter resources are exhausted
750  *    2. a message that will consume a partial credit will stop the
751  *    bundling process early
752  *    3. we drop below the minimum number of messages for a bundle
753  */
754 static void ath6kl_htc_tx_bundle(struct htc_endpoint *endpoint,
755 				 struct list_head *queue,
756 				 int *sent_bundle, int *n_bundle_pkts)
757 {
758 	struct htc_target *target = endpoint->target;
759 	struct hif_scatter_req *scat_req = NULL;
760 	int n_scat, n_sent_bundle = 0, tot_pkts_bundle = 0;
761 	int status;
762 	u32 txb_mask;
763 	u8 ac = WMM_NUM_AC;
764 
765 	if ((HTC_CTRL_RSVD_SVC != endpoint->svc_id) &&
766 	    (WMI_CONTROL_SVC != endpoint->svc_id))
767 		ac = target->dev->ar->ep2ac_map[endpoint->eid];
768 
769 	while (true) {
770 		status = 0;
771 		n_scat = get_queue_depth(queue);
772 		n_scat = min(n_scat, target->msg_per_bndl_max);
773 
774 		if (n_scat < HTC_MIN_HTC_MSGS_TO_BUNDLE)
775 			/* not enough to bundle */
776 			break;
777 
778 		scat_req = hif_scatter_req_get(target->dev->ar);
779 
780 		if (!scat_req) {
781 			/* no scatter resources  */
782 			ath6kl_dbg(ATH6KL_DBG_HTC,
783 				   "htc tx no more scatter resources\n");
784 			break;
785 		}
786 
787 		if ((ac < WMM_NUM_AC) && (ac != WMM_AC_BK)) {
788 			if (WMM_AC_BE == ac)
789 				/*
790 				 * BE, BK have priorities and bit
791 				 * positions reversed
792 				 */
793 				txb_mask = (1 << WMM_AC_BK);
794 			else
795 				/*
796 				 * any AC with priority lower than
797 				 * itself
798 				 */
799 				txb_mask = ((1 << ac) - 1);
800 
801 			/*
802 			 * when the scatter request resources drop below a
803 			 * certain threshold, disable Tx bundling for all
804 			 * AC's with priority lower than the current requesting
805 			 * AC. Otherwise re-enable Tx bundling for them
806 			 */
807 			if (scat_req->scat_q_depth < ATH6KL_SCATTER_REQS)
808 				target->tx_bndl_mask &= ~txb_mask;
809 			else
810 				target->tx_bndl_mask |= txb_mask;
811 		}
812 
813 		ath6kl_dbg(ATH6KL_DBG_HTC, "htc tx pkts to scatter: %d\n",
814 			   n_scat);
815 
816 		scat_req->len = 0;
817 		scat_req->scat_entries = 0;
818 
819 		status = ath6kl_htc_tx_setup_scat_list(target, endpoint,
820 						       scat_req, n_scat,
821 						       queue);
822 		if (status == -EAGAIN) {
823 			hif_scatter_req_add(target->dev->ar, scat_req);
824 			break;
825 		}
826 
827 		/* send path is always asynchronous */
828 		scat_req->complete = htc_async_tx_scat_complete;
829 		n_sent_bundle++;
830 		tot_pkts_bundle += scat_req->scat_entries;
831 
832 		ath6kl_dbg(ATH6KL_DBG_HTC,
833 			   "htc tx scatter bytes %d entries %d\n",
834 			   scat_req->len, scat_req->scat_entries);
835 		ath6kl_hif_submit_scat_req(target->dev, scat_req, false);
836 
837 		if (status)
838 			break;
839 	}
840 
841 	*sent_bundle = n_sent_bundle;
842 	*n_bundle_pkts = tot_pkts_bundle;
843 	ath6kl_dbg(ATH6KL_DBG_HTC, "htc tx bundle sent %d pkts\n",
844 		   n_sent_bundle);
845 
846 	return;
847 }
848 
849 static void ath6kl_htc_tx_from_queue(struct htc_target *target,
850 				     struct htc_endpoint *endpoint)
851 {
852 	struct list_head txq;
853 	struct htc_packet *packet;
854 	int bundle_sent;
855 	int n_pkts_bundle;
856 	u8 ac = WMM_NUM_AC;
857 
858 	spin_lock_bh(&target->tx_lock);
859 
860 	endpoint->tx_proc_cnt++;
861 	if (endpoint->tx_proc_cnt > 1) {
862 		endpoint->tx_proc_cnt--;
863 		spin_unlock_bh(&target->tx_lock);
864 		ath6kl_dbg(ATH6KL_DBG_HTC, "htc tx busy\n");
865 		return;
866 	}
867 
868 	/*
869 	 * drain the endpoint TX queue for transmission as long
870 	 * as we have enough credits.
871 	 */
872 	INIT_LIST_HEAD(&txq);
873 
874 	if ((HTC_CTRL_RSVD_SVC != endpoint->svc_id) &&
875 	    (WMI_CONTROL_SVC != endpoint->svc_id))
876 		ac = target->dev->ar->ep2ac_map[endpoint->eid];
877 
878 	while (true) {
879 
880 		if (list_empty(&endpoint->txq))
881 			break;
882 
883 		ath6kl_htc_tx_pkts_get(target, endpoint, &txq);
884 
885 		if (list_empty(&txq))
886 			break;
887 
888 		spin_unlock_bh(&target->tx_lock);
889 
890 		bundle_sent = 0;
891 		n_pkts_bundle = 0;
892 
893 		while (true) {
894 			/* try to send a bundle on each pass */
895 			if ((target->tx_bndl_mask) &&
896 			    (get_queue_depth(&txq) >=
897 			    HTC_MIN_HTC_MSGS_TO_BUNDLE)) {
898 				int temp1 = 0, temp2 = 0;
899 
900 				/* check if bundling is enabled for an AC */
901 				if (target->tx_bndl_mask & (1 << ac)) {
902 					ath6kl_htc_tx_bundle(endpoint, &txq,
903 							     &temp1, &temp2);
904 					bundle_sent += temp1;
905 					n_pkts_bundle += temp2;
906 				}
907 			}
908 
909 			if (list_empty(&txq))
910 				break;
911 
912 			packet = list_first_entry(&txq, struct htc_packet,
913 						  list);
914 			list_del(&packet->list);
915 
916 			ath6kl_htc_tx_prep_pkt(packet, packet->info.tx.flags,
917 					       0, packet->info.tx.seqno);
918 			ath6kl_htc_tx_issue(target, packet);
919 		}
920 
921 		spin_lock_bh(&target->tx_lock);
922 
923 		endpoint->ep_st.tx_bundles += bundle_sent;
924 		endpoint->ep_st.tx_pkt_bundled += n_pkts_bundle;
925 
926 		/*
927 		 * if an AC has bundling disabled and no tx bundling
928 		 * has occured continously for a certain number of TX,
929 		 * enable tx bundling for this AC
930 		 */
931 		if (!bundle_sent) {
932 			if (!(target->tx_bndl_mask & (1 << ac)) &&
933 			    (ac < WMM_NUM_AC)) {
934 				if (++target->ac_tx_count[ac] >=
935 					TX_RESUME_BUNDLE_THRESHOLD) {
936 					target->ac_tx_count[ac] = 0;
937 					target->tx_bndl_mask |= (1 << ac);
938 				}
939 			}
940 		} else {
941 			/* tx bundling will reset the counter */
942 			if (ac < WMM_NUM_AC)
943 				target->ac_tx_count[ac] = 0;
944 		}
945 	}
946 
947 	endpoint->tx_proc_cnt = 0;
948 	spin_unlock_bh(&target->tx_lock);
949 }
950 
951 static bool ath6kl_htc_tx_try(struct htc_target *target,
952 			      struct htc_endpoint *endpoint,
953 			      struct htc_packet *tx_pkt)
954 {
955 	struct htc_ep_callbacks ep_cb;
956 	int txq_depth;
957 	bool overflow = false;
958 
959 	ep_cb = endpoint->ep_cb;
960 
961 	spin_lock_bh(&target->tx_lock);
962 	txq_depth = get_queue_depth(&endpoint->txq);
963 	spin_unlock_bh(&target->tx_lock);
964 
965 	if (txq_depth >= endpoint->max_txq_depth)
966 		overflow = true;
967 
968 	if (overflow)
969 		ath6kl_dbg(ATH6KL_DBG_HTC,
970 			   "htc tx overflow ep %d depth %d max %d\n",
971 			   endpoint->eid, txq_depth,
972 			   endpoint->max_txq_depth);
973 
974 	if (overflow && ep_cb.tx_full) {
975 		if (ep_cb.tx_full(endpoint->target, tx_pkt) ==
976 		    HTC_SEND_FULL_DROP) {
977 			endpoint->ep_st.tx_dropped += 1;
978 			return false;
979 		}
980 	}
981 
982 	spin_lock_bh(&target->tx_lock);
983 	list_add_tail(&tx_pkt->list, &endpoint->txq);
984 	spin_unlock_bh(&target->tx_lock);
985 
986 	ath6kl_htc_tx_from_queue(target, endpoint);
987 
988 	return true;
989 }
990 
991 static void htc_chk_ep_txq(struct htc_target *target)
992 {
993 	struct htc_endpoint *endpoint;
994 	struct htc_endpoint_credit_dist *cred_dist;
995 
996 	/*
997 	 * Run through the credit distribution list to see if there are
998 	 * packets queued. NOTE: no locks need to be taken since the
999 	 * distribution list is not dynamic (cannot be re-ordered) and we
1000 	 * are not modifying any state.
1001 	 */
1002 	list_for_each_entry(cred_dist, &target->cred_dist_list, list) {
1003 		endpoint = cred_dist->htc_ep;
1004 
1005 		spin_lock_bh(&target->tx_lock);
1006 		if (!list_empty(&endpoint->txq)) {
1007 			ath6kl_dbg(ATH6KL_DBG_HTC,
1008 				   "htc creds ep %d credits %d pkts %d\n",
1009 				   cred_dist->endpoint,
1010 				   endpoint->cred_dist.credits,
1011 				   get_queue_depth(&endpoint->txq));
1012 			spin_unlock_bh(&target->tx_lock);
1013 			/*
1014 			 * Try to start the stalled queue, this list is
1015 			 * ordered by priority. If there are credits
1016 			 * available the highest priority queue will get a
1017 			 * chance to reclaim credits from lower priority
1018 			 * ones.
1019 			 */
1020 			ath6kl_htc_tx_from_queue(target, endpoint);
1021 			spin_lock_bh(&target->tx_lock);
1022 		}
1023 		spin_unlock_bh(&target->tx_lock);
1024 	}
1025 }
1026 
1027 static int htc_setup_tx_complete(struct htc_target *target)
1028 {
1029 	struct htc_packet *send_pkt = NULL;
1030 	int status;
1031 
1032 	send_pkt = htc_get_control_buf(target, true);
1033 
1034 	if (!send_pkt)
1035 		return -ENOMEM;
1036 
1037 	if (target->htc_tgt_ver >= HTC_VERSION_2P1) {
1038 		struct htc_setup_comp_ext_msg *setup_comp_ext;
1039 		u32 flags = 0;
1040 
1041 		setup_comp_ext =
1042 		    (struct htc_setup_comp_ext_msg *)send_pkt->buf;
1043 		memset(setup_comp_ext, 0, sizeof(*setup_comp_ext));
1044 		setup_comp_ext->msg_id =
1045 			cpu_to_le16(HTC_MSG_SETUP_COMPLETE_EX_ID);
1046 
1047 		if (target->msg_per_bndl_max > 0) {
1048 			/* Indicate HTC bundling to the target */
1049 			flags |= HTC_SETUP_COMP_FLG_RX_BNDL_EN;
1050 			setup_comp_ext->msg_per_rxbndl =
1051 						target->msg_per_bndl_max;
1052 		}
1053 
1054 		memcpy(&setup_comp_ext->flags, &flags,
1055 		       sizeof(setup_comp_ext->flags));
1056 		set_htc_pkt_info(send_pkt, NULL, (u8 *) setup_comp_ext,
1057 				 sizeof(struct htc_setup_comp_ext_msg),
1058 				 ENDPOINT_0, HTC_SERVICE_TX_PACKET_TAG);
1059 
1060 	} else {
1061 		struct htc_setup_comp_msg *setup_comp;
1062 		setup_comp = (struct htc_setup_comp_msg *)send_pkt->buf;
1063 		memset(setup_comp, 0, sizeof(struct htc_setup_comp_msg));
1064 		setup_comp->msg_id = cpu_to_le16(HTC_MSG_SETUP_COMPLETE_ID);
1065 		set_htc_pkt_info(send_pkt, NULL, (u8 *) setup_comp,
1066 				 sizeof(struct htc_setup_comp_msg),
1067 				 ENDPOINT_0, HTC_SERVICE_TX_PACKET_TAG);
1068 	}
1069 
1070 	/* we want synchronous operation */
1071 	send_pkt->completion = NULL;
1072 	ath6kl_htc_tx_prep_pkt(send_pkt, 0, 0, 0);
1073 	status = ath6kl_htc_tx_issue(target, send_pkt);
1074 
1075 	if (send_pkt != NULL)
1076 		htc_reclaim_txctrl_buf(target, send_pkt);
1077 
1078 	return status;
1079 }
1080 
1081 static void ath6kl_htc_set_credit_dist(struct htc_target *target,
1082 				struct ath6kl_htc_credit_info *credit_info,
1083 				u16 srvc_pri_order[], int list_len)
1084 {
1085 	struct htc_endpoint *endpoint;
1086 	int i, ep;
1087 
1088 	target->credit_info = credit_info;
1089 
1090 	list_add_tail(&target->endpoint[ENDPOINT_0].cred_dist.list,
1091 		      &target->cred_dist_list);
1092 
1093 	for (i = 0; i < list_len; i++) {
1094 		for (ep = ENDPOINT_1; ep < ENDPOINT_MAX; ep++) {
1095 			endpoint = &target->endpoint[ep];
1096 			if (endpoint->svc_id == srvc_pri_order[i]) {
1097 				list_add_tail(&endpoint->cred_dist.list,
1098 					      &target->cred_dist_list);
1099 				break;
1100 			}
1101 		}
1102 		if (ep >= ENDPOINT_MAX) {
1103 			WARN_ON(1);
1104 			return;
1105 		}
1106 	}
1107 }
1108 
1109 static int ath6kl_htc_mbox_tx(struct htc_target *target,
1110 			      struct htc_packet *packet)
1111 {
1112 	struct htc_endpoint *endpoint;
1113 	struct list_head queue;
1114 
1115 	ath6kl_dbg(ATH6KL_DBG_HTC,
1116 		   "htc tx ep id %d buf 0x%p len %d\n",
1117 		   packet->endpoint, packet->buf, packet->act_len);
1118 
1119 	if (packet->endpoint >= ENDPOINT_MAX) {
1120 		WARN_ON(1);
1121 		return -EINVAL;
1122 	}
1123 
1124 	endpoint = &target->endpoint[packet->endpoint];
1125 
1126 	if (!ath6kl_htc_tx_try(target, endpoint, packet)) {
1127 		packet->status = (target->htc_flags & HTC_OP_STATE_STOPPING) ?
1128 				 -ECANCELED : -ENOSPC;
1129 		INIT_LIST_HEAD(&queue);
1130 		list_add(&packet->list, &queue);
1131 		htc_tx_complete(endpoint, &queue);
1132 	}
1133 
1134 	return 0;
1135 }
1136 
1137 /* flush endpoint TX queue */
1138 static void ath6kl_htc_mbox_flush_txep(struct htc_target *target,
1139 			   enum htc_endpoint_id eid, u16 tag)
1140 {
1141 	struct htc_packet *packet, *tmp_pkt;
1142 	struct list_head discard_q, container;
1143 	struct htc_endpoint *endpoint = &target->endpoint[eid];
1144 
1145 	if (!endpoint->svc_id) {
1146 		WARN_ON(1);
1147 		return;
1148 	}
1149 
1150 	/* initialize the discard queue */
1151 	INIT_LIST_HEAD(&discard_q);
1152 
1153 	spin_lock_bh(&target->tx_lock);
1154 
1155 	list_for_each_entry_safe(packet, tmp_pkt, &endpoint->txq, list) {
1156 		if ((tag == HTC_TX_PACKET_TAG_ALL) ||
1157 		    (tag == packet->info.tx.tag))
1158 			list_move_tail(&packet->list, &discard_q);
1159 	}
1160 
1161 	spin_unlock_bh(&target->tx_lock);
1162 
1163 	list_for_each_entry_safe(packet, tmp_pkt, &discard_q, list) {
1164 		packet->status = -ECANCELED;
1165 		list_del(&packet->list);
1166 		ath6kl_dbg(ATH6KL_DBG_HTC,
1167 			   "htc tx flushing pkt 0x%p len %d  ep %d tag 0x%x\n",
1168 			   packet, packet->act_len,
1169 			   packet->endpoint, packet->info.tx.tag);
1170 
1171 		INIT_LIST_HEAD(&container);
1172 		list_add_tail(&packet->list, &container);
1173 		htc_tx_complete(endpoint, &container);
1174 	}
1175 
1176 }
1177 
1178 static void ath6kl_htc_flush_txep_all(struct htc_target *target)
1179 {
1180 	struct htc_endpoint *endpoint;
1181 	int i;
1182 
1183 	dump_cred_dist_stats(target);
1184 
1185 	for (i = ENDPOINT_0; i < ENDPOINT_MAX; i++) {
1186 		endpoint = &target->endpoint[i];
1187 		if (endpoint->svc_id == 0)
1188 			/* not in use.. */
1189 			continue;
1190 		ath6kl_htc_mbox_flush_txep(target, i, HTC_TX_PACKET_TAG_ALL);
1191 	}
1192 }
1193 
1194 static void ath6kl_htc_mbox_activity_changed(struct htc_target *target,
1195 					     enum htc_endpoint_id eid,
1196 					     bool active)
1197 {
1198 	struct htc_endpoint *endpoint = &target->endpoint[eid];
1199 	bool dist = false;
1200 
1201 	if (endpoint->svc_id == 0) {
1202 		WARN_ON(1);
1203 		return;
1204 	}
1205 
1206 	spin_lock_bh(&target->tx_lock);
1207 
1208 	if (active) {
1209 		if (!(endpoint->cred_dist.dist_flags & HTC_EP_ACTIVE)) {
1210 			endpoint->cred_dist.dist_flags |= HTC_EP_ACTIVE;
1211 			dist = true;
1212 		}
1213 	} else {
1214 		if (endpoint->cred_dist.dist_flags & HTC_EP_ACTIVE) {
1215 			endpoint->cred_dist.dist_flags &= ~HTC_EP_ACTIVE;
1216 			dist = true;
1217 		}
1218 	}
1219 
1220 	if (dist) {
1221 		endpoint->cred_dist.txq_depth =
1222 			get_queue_depth(&endpoint->txq);
1223 
1224 		ath6kl_dbg(ATH6KL_DBG_HTC,
1225 			   "htc tx activity ctxt 0x%p dist 0x%p\n",
1226 			   target->credit_info, &target->cred_dist_list);
1227 
1228 		ath6kl_credit_distribute(target->credit_info,
1229 					 &target->cred_dist_list,
1230 					 HTC_CREDIT_DIST_ACTIVITY_CHANGE);
1231 	}
1232 
1233 	spin_unlock_bh(&target->tx_lock);
1234 
1235 	if (dist && !active)
1236 		htc_chk_ep_txq(target);
1237 }
1238 
1239 /* HTC Rx */
1240 
1241 static inline void ath6kl_htc_rx_update_stats(struct htc_endpoint *endpoint,
1242 					      int n_look_ahds)
1243 {
1244 	endpoint->ep_st.rx_pkts++;
1245 	if (n_look_ahds == 1)
1246 		endpoint->ep_st.rx_lkahds++;
1247 	else if (n_look_ahds > 1)
1248 		endpoint->ep_st.rx_bundle_lkahd++;
1249 }
1250 
1251 static inline bool htc_valid_rx_frame_len(struct htc_target *target,
1252 					  enum htc_endpoint_id eid, int len)
1253 {
1254 	return (eid == target->dev->ar->ctrl_ep) ?
1255 		len <= ATH6KL_BUFFER_SIZE : len <= ATH6KL_AMSDU_BUFFER_SIZE;
1256 }
1257 
1258 static int htc_add_rxbuf(struct htc_target *target, struct htc_packet *packet)
1259 {
1260 	struct list_head queue;
1261 
1262 	INIT_LIST_HEAD(&queue);
1263 	list_add_tail(&packet->list, &queue);
1264 	return ath6kl_htc_mbox_add_rxbuf_multiple(target, &queue);
1265 }
1266 
1267 static void htc_reclaim_rxbuf(struct htc_target *target,
1268 			      struct htc_packet *packet,
1269 			      struct htc_endpoint *ep)
1270 {
1271 	if (packet->info.rx.rx_flags & HTC_RX_PKT_NO_RECYCLE) {
1272 		htc_rxpkt_reset(packet);
1273 		packet->status = -ECANCELED;
1274 		ep->ep_cb.rx(ep->target, packet);
1275 	} else {
1276 		htc_rxpkt_reset(packet);
1277 		htc_add_rxbuf((void *)(target), packet);
1278 	}
1279 }
1280 
1281 static void reclaim_rx_ctrl_buf(struct htc_target *target,
1282 				struct htc_packet *packet)
1283 {
1284 	spin_lock_bh(&target->htc_lock);
1285 	list_add_tail(&packet->list, &target->free_ctrl_rxbuf);
1286 	spin_unlock_bh(&target->htc_lock);
1287 }
1288 
1289 static int ath6kl_htc_rx_packet(struct htc_target *target,
1290 				struct htc_packet *packet,
1291 				u32 rx_len)
1292 {
1293 	struct ath6kl_device *dev = target->dev;
1294 	u32 padded_len;
1295 	int status;
1296 
1297 	padded_len = CALC_TXRX_PADDED_LEN(target, rx_len);
1298 
1299 	if (padded_len > packet->buf_len) {
1300 		ath6kl_err("not enough receive space for packet - padlen %d recvlen %d bufferlen %d\n",
1301 			   padded_len, rx_len, packet->buf_len);
1302 		return -ENOMEM;
1303 	}
1304 
1305 	ath6kl_dbg(ATH6KL_DBG_HTC,
1306 		   "htc rx 0x%p hdr x%x len %d mbox 0x%x\n",
1307 		   packet, packet->info.rx.exp_hdr,
1308 		   padded_len, dev->ar->mbox_info.htc_addr);
1309 
1310 	status = hif_read_write_sync(dev->ar,
1311 				     dev->ar->mbox_info.htc_addr,
1312 				     packet->buf, padded_len,
1313 				     HIF_RD_SYNC_BLOCK_FIX);
1314 
1315 	packet->status = status;
1316 
1317 	return status;
1318 }
1319 
1320 /*
1321  * optimization for recv packets, we can indicate a
1322  * "hint" that there are more  single-packets to fetch
1323  * on this endpoint.
1324  */
1325 static void ath6kl_htc_rx_set_indicate(u32 lk_ahd,
1326 				       struct htc_endpoint *endpoint,
1327 				       struct htc_packet *packet)
1328 {
1329 	struct htc_frame_hdr *htc_hdr = (struct htc_frame_hdr *)&lk_ahd;
1330 
1331 	if (htc_hdr->eid == packet->endpoint) {
1332 		if (!list_empty(&endpoint->rx_bufq))
1333 			packet->info.rx.indicat_flags |=
1334 					HTC_RX_FLAGS_INDICATE_MORE_PKTS;
1335 	}
1336 }
1337 
1338 static void ath6kl_htc_rx_chk_water_mark(struct htc_endpoint *endpoint)
1339 {
1340 	struct htc_ep_callbacks ep_cb = endpoint->ep_cb;
1341 
1342 	if (ep_cb.rx_refill_thresh > 0) {
1343 		spin_lock_bh(&endpoint->target->rx_lock);
1344 		if (get_queue_depth(&endpoint->rx_bufq)
1345 		    < ep_cb.rx_refill_thresh) {
1346 			spin_unlock_bh(&endpoint->target->rx_lock);
1347 			ep_cb.rx_refill(endpoint->target, endpoint->eid);
1348 			return;
1349 		}
1350 		spin_unlock_bh(&endpoint->target->rx_lock);
1351 	}
1352 }
1353 
1354 /* This function is called with rx_lock held */
1355 static int ath6kl_htc_rx_setup(struct htc_target *target,
1356 			       struct htc_endpoint *ep,
1357 			       u32 *lk_ahds, struct list_head *queue, int n_msg)
1358 {
1359 	struct htc_packet *packet;
1360 	/* FIXME: type of lk_ahds can't be right */
1361 	struct htc_frame_hdr *htc_hdr = (struct htc_frame_hdr *)lk_ahds;
1362 	struct htc_ep_callbacks ep_cb;
1363 	int status = 0, j, full_len;
1364 	bool no_recycle;
1365 
1366 	full_len = CALC_TXRX_PADDED_LEN(target,
1367 					le16_to_cpu(htc_hdr->payld_len) +
1368 					sizeof(*htc_hdr));
1369 
1370 	if (!htc_valid_rx_frame_len(target, ep->eid, full_len)) {
1371 		ath6kl_warn("Rx buffer requested with invalid length htc_hdr:eid %d, flags 0x%x, len %d\n",
1372 			    htc_hdr->eid, htc_hdr->flags,
1373 			    le16_to_cpu(htc_hdr->payld_len));
1374 		return -EINVAL;
1375 	}
1376 
1377 	ep_cb = ep->ep_cb;
1378 	for (j = 0; j < n_msg; j++) {
1379 
1380 		/*
1381 		 * Reset flag, any packets allocated using the
1382 		 * rx_alloc() API cannot be recycled on
1383 		 * cleanup,they must be explicitly returned.
1384 		 */
1385 		no_recycle = false;
1386 
1387 		if (ep_cb.rx_allocthresh &&
1388 		    (full_len > ep_cb.rx_alloc_thresh)) {
1389 			ep->ep_st.rx_alloc_thresh_hit += 1;
1390 			ep->ep_st.rxalloc_thresh_byte +=
1391 				le16_to_cpu(htc_hdr->payld_len);
1392 
1393 			spin_unlock_bh(&target->rx_lock);
1394 			no_recycle = true;
1395 
1396 			packet = ep_cb.rx_allocthresh(ep->target, ep->eid,
1397 						      full_len);
1398 			spin_lock_bh(&target->rx_lock);
1399 		} else {
1400 			/* refill handler is being used */
1401 			if (list_empty(&ep->rx_bufq)) {
1402 				if (ep_cb.rx_refill) {
1403 					spin_unlock_bh(&target->rx_lock);
1404 					ep_cb.rx_refill(ep->target, ep->eid);
1405 					spin_lock_bh(&target->rx_lock);
1406 				}
1407 			}
1408 
1409 			if (list_empty(&ep->rx_bufq))
1410 				packet = NULL;
1411 			else {
1412 				packet = list_first_entry(&ep->rx_bufq,
1413 						struct htc_packet, list);
1414 				list_del(&packet->list);
1415 			}
1416 		}
1417 
1418 		if (!packet) {
1419 			target->rx_st_flags |= HTC_RECV_WAIT_BUFFERS;
1420 			target->ep_waiting = ep->eid;
1421 			return -ENOSPC;
1422 		}
1423 
1424 		/* clear flags */
1425 		packet->info.rx.rx_flags = 0;
1426 		packet->info.rx.indicat_flags = 0;
1427 		packet->status = 0;
1428 
1429 		if (no_recycle)
1430 			/*
1431 			 * flag that these packets cannot be
1432 			 * recycled, they have to be returned to
1433 			 * the user
1434 			 */
1435 			packet->info.rx.rx_flags |= HTC_RX_PKT_NO_RECYCLE;
1436 
1437 		/* Caller needs to free this upon any failure */
1438 		list_add_tail(&packet->list, queue);
1439 
1440 		if (target->htc_flags & HTC_OP_STATE_STOPPING) {
1441 			status = -ECANCELED;
1442 			break;
1443 		}
1444 
1445 		if (j) {
1446 			packet->info.rx.rx_flags |= HTC_RX_PKT_REFRESH_HDR;
1447 			packet->info.rx.exp_hdr = 0xFFFFFFFF;
1448 		} else
1449 			/* set expected look ahead */
1450 			packet->info.rx.exp_hdr = *lk_ahds;
1451 
1452 		packet->act_len = le16_to_cpu(htc_hdr->payld_len) +
1453 			HTC_HDR_LENGTH;
1454 	}
1455 
1456 	return status;
1457 }
1458 
1459 static int ath6kl_htc_rx_alloc(struct htc_target *target,
1460 			       u32 lk_ahds[], int msg,
1461 			       struct htc_endpoint *endpoint,
1462 			       struct list_head *queue)
1463 {
1464 	int status = 0;
1465 	struct htc_packet *packet, *tmp_pkt;
1466 	struct htc_frame_hdr *htc_hdr;
1467 	int i, n_msg;
1468 
1469 	spin_lock_bh(&target->rx_lock);
1470 
1471 	for (i = 0; i < msg; i++) {
1472 
1473 		htc_hdr = (struct htc_frame_hdr *)&lk_ahds[i];
1474 
1475 		if (htc_hdr->eid >= ENDPOINT_MAX) {
1476 			ath6kl_err("invalid ep in look-ahead: %d\n",
1477 				   htc_hdr->eid);
1478 			status = -ENOMEM;
1479 			break;
1480 		}
1481 
1482 		if (htc_hdr->eid != endpoint->eid) {
1483 			ath6kl_err("invalid ep in look-ahead: %d should be : %d (index:%d)\n",
1484 				   htc_hdr->eid, endpoint->eid, i);
1485 			status = -ENOMEM;
1486 			break;
1487 		}
1488 
1489 		if (le16_to_cpu(htc_hdr->payld_len) > HTC_MAX_PAYLOAD_LENGTH) {
1490 			ath6kl_err("payload len %d exceeds max htc : %d !\n",
1491 				   htc_hdr->payld_len,
1492 				   (u32) HTC_MAX_PAYLOAD_LENGTH);
1493 			status = -ENOMEM;
1494 			break;
1495 		}
1496 
1497 		if (endpoint->svc_id == 0) {
1498 			ath6kl_err("ep %d is not connected !\n", htc_hdr->eid);
1499 			status = -ENOMEM;
1500 			break;
1501 		}
1502 
1503 		if (htc_hdr->flags & HTC_FLG_RX_BNDL_CNT) {
1504 			/*
1505 			 * HTC header indicates that every packet to follow
1506 			 * has the same padded length so that it can be
1507 			 * optimally fetched as a full bundle.
1508 			 */
1509 			n_msg = (htc_hdr->flags & HTC_FLG_RX_BNDL_CNT) >>
1510 				HTC_FLG_RX_BNDL_CNT_S;
1511 
1512 			/* the count doesn't include the starter frame */
1513 			n_msg++;
1514 			if (n_msg > target->msg_per_bndl_max) {
1515 				status = -ENOMEM;
1516 				break;
1517 			}
1518 
1519 			endpoint->ep_st.rx_bundle_from_hdr += 1;
1520 			ath6kl_dbg(ATH6KL_DBG_HTC,
1521 				   "htc rx bundle pkts %d\n",
1522 				   n_msg);
1523 		} else
1524 			/* HTC header only indicates 1 message to fetch */
1525 			n_msg = 1;
1526 
1527 		/* Setup packet buffers for each message */
1528 		status = ath6kl_htc_rx_setup(target, endpoint, &lk_ahds[i],
1529 					     queue, n_msg);
1530 
1531 		/*
1532 		 * This is due to unavailabilty of buffers to rx entire data.
1533 		 * Return no error so that free buffers from queue can be used
1534 		 * to receive partial data.
1535 		 */
1536 		if (status == -ENOSPC) {
1537 			spin_unlock_bh(&target->rx_lock);
1538 			return 0;
1539 		}
1540 
1541 		if (status)
1542 			break;
1543 	}
1544 
1545 	spin_unlock_bh(&target->rx_lock);
1546 
1547 	if (status) {
1548 		list_for_each_entry_safe(packet, tmp_pkt, queue, list) {
1549 			list_del(&packet->list);
1550 			htc_reclaim_rxbuf(target, packet,
1551 					  &target->endpoint[packet->endpoint]);
1552 		}
1553 	}
1554 
1555 	return status;
1556 }
1557 
1558 static void htc_ctrl_rx(struct htc_target *context, struct htc_packet *packets)
1559 {
1560 	if (packets->endpoint != ENDPOINT_0) {
1561 		WARN_ON(1);
1562 		return;
1563 	}
1564 
1565 	if (packets->status == -ECANCELED) {
1566 		reclaim_rx_ctrl_buf(context, packets);
1567 		return;
1568 	}
1569 
1570 	if (packets->act_len > 0) {
1571 		ath6kl_err("htc_ctrl_rx, got message with len:%zu\n",
1572 			   packets->act_len + HTC_HDR_LENGTH);
1573 
1574 		ath6kl_dbg_dump(ATH6KL_DBG_HTC,
1575 				"htc rx unexpected endpoint 0 message", "",
1576 				packets->buf - HTC_HDR_LENGTH,
1577 				packets->act_len + HTC_HDR_LENGTH);
1578 	}
1579 
1580 	htc_reclaim_rxbuf(context, packets, &context->endpoint[0]);
1581 }
1582 
1583 static void htc_proc_cred_rpt(struct htc_target *target,
1584 			      struct htc_credit_report *rpt,
1585 			      int n_entries,
1586 			      enum htc_endpoint_id from_ep)
1587 {
1588 	struct htc_endpoint *endpoint;
1589 	int tot_credits = 0, i;
1590 	bool dist = false;
1591 
1592 	spin_lock_bh(&target->tx_lock);
1593 
1594 	for (i = 0; i < n_entries; i++, rpt++) {
1595 		if (rpt->eid >= ENDPOINT_MAX) {
1596 			WARN_ON(1);
1597 			spin_unlock_bh(&target->tx_lock);
1598 			return;
1599 		}
1600 
1601 		endpoint = &target->endpoint[rpt->eid];
1602 
1603 		ath6kl_dbg(ATH6KL_DBG_CREDIT,
1604 			   "credit report ep %d credits %d\n",
1605 			   rpt->eid, rpt->credits);
1606 
1607 		endpoint->ep_st.tx_cred_rpt += 1;
1608 		endpoint->ep_st.cred_retnd += rpt->credits;
1609 
1610 		if (from_ep == rpt->eid) {
1611 			/*
1612 			 * This credit report arrived on the same endpoint
1613 			 * indicating it arrived in an RX packet.
1614 			 */
1615 			endpoint->ep_st.cred_from_rx += rpt->credits;
1616 			endpoint->ep_st.cred_rpt_from_rx += 1;
1617 		} else if (from_ep == ENDPOINT_0) {
1618 			/* credit arrived on endpoint 0 as a NULL message */
1619 			endpoint->ep_st.cred_from_ep0 += rpt->credits;
1620 			endpoint->ep_st.cred_rpt_ep0 += 1;
1621 		} else {
1622 			endpoint->ep_st.cred_from_other += rpt->credits;
1623 			endpoint->ep_st.cred_rpt_from_other += 1;
1624 		}
1625 
1626 		if (rpt->eid == ENDPOINT_0)
1627 			/* always give endpoint 0 credits back */
1628 			endpoint->cred_dist.credits += rpt->credits;
1629 		else {
1630 			endpoint->cred_dist.cred_to_dist += rpt->credits;
1631 			dist = true;
1632 		}
1633 
1634 		/*
1635 		 * Refresh tx depth for distribution function that will
1636 		 * recover these credits NOTE: this is only valid when
1637 		 * there are credits to recover!
1638 		 */
1639 		endpoint->cred_dist.txq_depth =
1640 			get_queue_depth(&endpoint->txq);
1641 
1642 		tot_credits += rpt->credits;
1643 	}
1644 
1645 	if (dist) {
1646 		/*
1647 		 * This was a credit return based on a completed send
1648 		 * operations note, this is done with the lock held
1649 		 */
1650 		ath6kl_credit_distribute(target->credit_info,
1651 					 &target->cred_dist_list,
1652 					 HTC_CREDIT_DIST_SEND_COMPLETE);
1653 	}
1654 
1655 	spin_unlock_bh(&target->tx_lock);
1656 
1657 	if (tot_credits)
1658 		htc_chk_ep_txq(target);
1659 }
1660 
1661 static int htc_parse_trailer(struct htc_target *target,
1662 			     struct htc_record_hdr *record,
1663 			     u8 *record_buf, u32 *next_lk_ahds,
1664 			     enum htc_endpoint_id endpoint,
1665 			     int *n_lk_ahds)
1666 {
1667 	struct htc_bundle_lkahd_rpt *bundle_lkahd_rpt;
1668 	struct htc_lookahead_report *lk_ahd;
1669 	int len;
1670 
1671 	switch (record->rec_id) {
1672 	case HTC_RECORD_CREDITS:
1673 		len = record->len / sizeof(struct htc_credit_report);
1674 		if (!len) {
1675 			WARN_ON(1);
1676 			return -EINVAL;
1677 		}
1678 
1679 		htc_proc_cred_rpt(target,
1680 				  (struct htc_credit_report *) record_buf,
1681 				  len, endpoint);
1682 		break;
1683 	case HTC_RECORD_LOOKAHEAD:
1684 		len = record->len / sizeof(*lk_ahd);
1685 		if (!len) {
1686 			WARN_ON(1);
1687 			return -EINVAL;
1688 		}
1689 
1690 		lk_ahd = (struct htc_lookahead_report *) record_buf;
1691 		if ((lk_ahd->pre_valid == ((~lk_ahd->post_valid) & 0xFF)) &&
1692 		    next_lk_ahds) {
1693 
1694 			ath6kl_dbg(ATH6KL_DBG_HTC,
1695 				   "htc rx lk_ahd found pre_valid 0x%x post_valid 0x%x\n",
1696 				   lk_ahd->pre_valid, lk_ahd->post_valid);
1697 
1698 			/* look ahead bytes are valid, copy them over */
1699 			memcpy((u8 *)&next_lk_ahds[0], lk_ahd->lk_ahd, 4);
1700 
1701 			ath6kl_dbg_dump(ATH6KL_DBG_HTC,
1702 					"htc rx next look ahead",
1703 					"", next_lk_ahds, 4);
1704 
1705 			*n_lk_ahds = 1;
1706 		}
1707 		break;
1708 	case HTC_RECORD_LOOKAHEAD_BUNDLE:
1709 		len = record->len / sizeof(*bundle_lkahd_rpt);
1710 		if (!len || (len > HTC_HOST_MAX_MSG_PER_BUNDLE)) {
1711 			WARN_ON(1);
1712 			return -EINVAL;
1713 		}
1714 
1715 		if (next_lk_ahds) {
1716 			int i;
1717 
1718 			bundle_lkahd_rpt =
1719 				(struct htc_bundle_lkahd_rpt *) record_buf;
1720 
1721 			ath6kl_dbg_dump(ATH6KL_DBG_HTC, "htc rx bundle lk_ahd",
1722 					"", record_buf, record->len);
1723 
1724 			for (i = 0; i < len; i++) {
1725 				memcpy((u8 *)&next_lk_ahds[i],
1726 				       bundle_lkahd_rpt->lk_ahd, 4);
1727 				bundle_lkahd_rpt++;
1728 			}
1729 
1730 			*n_lk_ahds = i;
1731 		}
1732 		break;
1733 	default:
1734 		ath6kl_err("unhandled record: id:%d len:%d\n",
1735 			   record->rec_id, record->len);
1736 		break;
1737 	}
1738 
1739 	return 0;
1740 
1741 }
1742 
1743 static int htc_proc_trailer(struct htc_target *target,
1744 			    u8 *buf, int len, u32 *next_lk_ahds,
1745 			    int *n_lk_ahds, enum htc_endpoint_id endpoint)
1746 {
1747 	struct htc_record_hdr *record;
1748 	int orig_len;
1749 	int status;
1750 	u8 *record_buf;
1751 	u8 *orig_buf;
1752 
1753 	ath6kl_dbg(ATH6KL_DBG_HTC, "htc rx trailer len %d\n", len);
1754 	ath6kl_dbg_dump(ATH6KL_DBG_HTC, NULL, "", buf, len);
1755 
1756 	orig_buf = buf;
1757 	orig_len = len;
1758 	status = 0;
1759 
1760 	while (len > 0) {
1761 
1762 		if (len < sizeof(struct htc_record_hdr)) {
1763 			status = -ENOMEM;
1764 			break;
1765 		}
1766 		/* these are byte aligned structs */
1767 		record = (struct htc_record_hdr *) buf;
1768 		len -= sizeof(struct htc_record_hdr);
1769 		buf += sizeof(struct htc_record_hdr);
1770 
1771 		if (record->len > len) {
1772 			ath6kl_err("invalid record len: %d (id:%d) buf has: %d bytes left\n",
1773 				   record->len, record->rec_id, len);
1774 			status = -ENOMEM;
1775 			break;
1776 		}
1777 		record_buf = buf;
1778 
1779 		status = htc_parse_trailer(target, record, record_buf,
1780 					   next_lk_ahds, endpoint, n_lk_ahds);
1781 
1782 		if (status)
1783 			break;
1784 
1785 		/* advance buffer past this record for next time around */
1786 		buf += record->len;
1787 		len -= record->len;
1788 	}
1789 
1790 	if (status)
1791 		ath6kl_dbg_dump(ATH6KL_DBG_HTC, "htc rx bad trailer",
1792 				"", orig_buf, orig_len);
1793 
1794 	return status;
1795 }
1796 
1797 static int ath6kl_htc_rx_process_hdr(struct htc_target *target,
1798 				     struct htc_packet *packet,
1799 				     u32 *next_lkahds, int *n_lkahds)
1800 {
1801 	int status = 0;
1802 	u16 payload_len;
1803 	u32 lk_ahd;
1804 	struct htc_frame_hdr *htc_hdr = (struct htc_frame_hdr *)packet->buf;
1805 
1806 	if (n_lkahds != NULL)
1807 		*n_lkahds = 0;
1808 
1809 	/*
1810 	 * NOTE: we cannot assume the alignment of buf, so we use the safe
1811 	 * macros to retrieve 16 bit fields.
1812 	 */
1813 	payload_len = le16_to_cpu(get_unaligned(&htc_hdr->payld_len));
1814 
1815 	memcpy((u8 *)&lk_ahd, packet->buf, sizeof(lk_ahd));
1816 
1817 	if (packet->info.rx.rx_flags & HTC_RX_PKT_REFRESH_HDR) {
1818 		/*
1819 		 * Refresh the expected header and the actual length as it
1820 		 * was unknown when this packet was grabbed as part of the
1821 		 * bundle.
1822 		 */
1823 		packet->info.rx.exp_hdr = lk_ahd;
1824 		packet->act_len = payload_len + HTC_HDR_LENGTH;
1825 
1826 		/* validate the actual header that was refreshed  */
1827 		if (packet->act_len > packet->buf_len) {
1828 			ath6kl_err("refreshed hdr payload len (%d) in bundled recv is invalid (hdr: 0x%X)\n",
1829 				   payload_len, lk_ahd);
1830 			/*
1831 			 * Limit this to max buffer just to print out some
1832 			 * of the buffer.
1833 			 */
1834 			packet->act_len = min(packet->act_len, packet->buf_len);
1835 			status = -ENOMEM;
1836 			goto fail_rx;
1837 		}
1838 
1839 		if (packet->endpoint != htc_hdr->eid) {
1840 			ath6kl_err("refreshed hdr ep (%d) does not match expected ep (%d)\n",
1841 				   htc_hdr->eid, packet->endpoint);
1842 			status = -ENOMEM;
1843 			goto fail_rx;
1844 		}
1845 	}
1846 
1847 	if (lk_ahd != packet->info.rx.exp_hdr) {
1848 		ath6kl_err("%s(): lk_ahd mismatch! (pPkt:0x%p flags:0x%X)\n",
1849 			   __func__, packet, packet->info.rx.rx_flags);
1850 		ath6kl_dbg_dump(ATH6KL_DBG_HTC, "htc rx expected lk_ahd",
1851 				"", &packet->info.rx.exp_hdr, 4);
1852 		ath6kl_dbg_dump(ATH6KL_DBG_HTC, "htc rx current header",
1853 				"", (u8 *)&lk_ahd, sizeof(lk_ahd));
1854 		status = -ENOMEM;
1855 		goto fail_rx;
1856 	}
1857 
1858 	if (htc_hdr->flags & HTC_FLG_RX_TRAILER) {
1859 		if (htc_hdr->ctrl[0] < sizeof(struct htc_record_hdr) ||
1860 		    htc_hdr->ctrl[0] > payload_len) {
1861 			ath6kl_err("%s(): invalid hdr (payload len should be :%d, CB[0] is:%d)\n",
1862 				   __func__, payload_len, htc_hdr->ctrl[0]);
1863 			status = -ENOMEM;
1864 			goto fail_rx;
1865 		}
1866 
1867 		if (packet->info.rx.rx_flags & HTC_RX_PKT_IGNORE_LOOKAHEAD) {
1868 			next_lkahds = NULL;
1869 			n_lkahds = NULL;
1870 		}
1871 
1872 		status = htc_proc_trailer(target, packet->buf + HTC_HDR_LENGTH
1873 					  + payload_len - htc_hdr->ctrl[0],
1874 					  htc_hdr->ctrl[0], next_lkahds,
1875 					   n_lkahds, packet->endpoint);
1876 
1877 		if (status)
1878 			goto fail_rx;
1879 
1880 		packet->act_len -= htc_hdr->ctrl[0];
1881 	}
1882 
1883 	packet->buf += HTC_HDR_LENGTH;
1884 	packet->act_len -= HTC_HDR_LENGTH;
1885 
1886 fail_rx:
1887 	if (status)
1888 		ath6kl_dbg_dump(ATH6KL_DBG_HTC, "htc rx bad packet",
1889 				"", packet->buf, packet->act_len);
1890 
1891 	return status;
1892 }
1893 
1894 static void ath6kl_htc_rx_complete(struct htc_endpoint *endpoint,
1895 				   struct htc_packet *packet)
1896 {
1897 		ath6kl_dbg(ATH6KL_DBG_HTC,
1898 			   "htc rx complete ep %d packet 0x%p\n",
1899 			   endpoint->eid, packet);
1900 		endpoint->ep_cb.rx(endpoint->target, packet);
1901 }
1902 
1903 static int ath6kl_htc_rx_bundle(struct htc_target *target,
1904 				struct list_head *rxq,
1905 				struct list_head *sync_compq,
1906 				int *n_pkt_fetched, bool part_bundle)
1907 {
1908 	struct hif_scatter_req *scat_req;
1909 	struct htc_packet *packet;
1910 	int rem_space = target->max_rx_bndl_sz;
1911 	int n_scat_pkt, status = 0, i, len;
1912 
1913 	n_scat_pkt = get_queue_depth(rxq);
1914 	n_scat_pkt = min(n_scat_pkt, target->msg_per_bndl_max);
1915 
1916 	if ((get_queue_depth(rxq) - n_scat_pkt) > 0) {
1917 		/*
1918 		 * We were forced to split this bundle receive operation
1919 		 * all packets in this partial bundle must have their
1920 		 * lookaheads ignored.
1921 		 */
1922 		part_bundle = true;
1923 
1924 		/*
1925 		 * This would only happen if the target ignored our max
1926 		 * bundle limit.
1927 		 */
1928 		ath6kl_warn("%s(): partial bundle detected num:%d , %d\n",
1929 			    __func__, get_queue_depth(rxq), n_scat_pkt);
1930 	}
1931 
1932 	len = 0;
1933 
1934 	ath6kl_dbg(ATH6KL_DBG_HTC,
1935 		   "htc rx bundle depth %d pkts %d\n",
1936 		   get_queue_depth(rxq), n_scat_pkt);
1937 
1938 	scat_req = hif_scatter_req_get(target->dev->ar);
1939 
1940 	if (scat_req == NULL)
1941 		goto fail_rx_pkt;
1942 
1943 	for (i = 0; i < n_scat_pkt; i++) {
1944 		int pad_len;
1945 
1946 		packet = list_first_entry(rxq, struct htc_packet, list);
1947 		list_del(&packet->list);
1948 
1949 		pad_len = CALC_TXRX_PADDED_LEN(target,
1950 						   packet->act_len);
1951 
1952 		if ((rem_space - pad_len) < 0) {
1953 			list_add(&packet->list, rxq);
1954 			break;
1955 		}
1956 
1957 		rem_space -= pad_len;
1958 
1959 		if (part_bundle || (i < (n_scat_pkt - 1)))
1960 			/*
1961 			 * Packet 0..n-1 cannot be checked for look-aheads
1962 			 * since we are fetching a bundle the last packet
1963 			 * however can have it's lookahead used
1964 			 */
1965 			packet->info.rx.rx_flags |=
1966 			    HTC_RX_PKT_IGNORE_LOOKAHEAD;
1967 
1968 		/* NOTE: 1 HTC packet per scatter entry */
1969 		scat_req->scat_list[i].buf = packet->buf;
1970 		scat_req->scat_list[i].len = pad_len;
1971 
1972 		packet->info.rx.rx_flags |= HTC_RX_PKT_PART_OF_BUNDLE;
1973 
1974 		list_add_tail(&packet->list, sync_compq);
1975 
1976 		WARN_ON(!scat_req->scat_list[i].len);
1977 		len += scat_req->scat_list[i].len;
1978 	}
1979 
1980 	scat_req->len = len;
1981 	scat_req->scat_entries = i;
1982 
1983 	status = ath6kl_hif_submit_scat_req(target->dev, scat_req, true);
1984 
1985 	if (!status)
1986 		*n_pkt_fetched = i;
1987 
1988 	/* free scatter request */
1989 	hif_scatter_req_add(target->dev->ar, scat_req);
1990 
1991 fail_rx_pkt:
1992 
1993 	return status;
1994 }
1995 
1996 static int ath6kl_htc_rx_process_packets(struct htc_target *target,
1997 					 struct list_head *comp_pktq,
1998 					 u32 lk_ahds[],
1999 					 int *n_lk_ahd)
2000 {
2001 	struct htc_packet *packet, *tmp_pkt;
2002 	struct htc_endpoint *ep;
2003 	int status = 0;
2004 
2005 	list_for_each_entry_safe(packet, tmp_pkt, comp_pktq, list) {
2006 		ep = &target->endpoint[packet->endpoint];
2007 
2008 		/* process header for each of the recv packet */
2009 		status = ath6kl_htc_rx_process_hdr(target, packet, lk_ahds,
2010 						   n_lk_ahd);
2011 		if (status)
2012 			return status;
2013 
2014 		list_del(&packet->list);
2015 
2016 		if (list_empty(comp_pktq)) {
2017 			/*
2018 			 * Last packet's more packet flag is set
2019 			 * based on the lookahead.
2020 			 */
2021 			if (*n_lk_ahd > 0)
2022 				ath6kl_htc_rx_set_indicate(lk_ahds[0],
2023 							   ep, packet);
2024 		} else
2025 			/*
2026 			 * Packets in a bundle automatically have
2027 			 * this flag set.
2028 			 */
2029 			packet->info.rx.indicat_flags |=
2030 				HTC_RX_FLAGS_INDICATE_MORE_PKTS;
2031 
2032 		ath6kl_htc_rx_update_stats(ep, *n_lk_ahd);
2033 
2034 		if (packet->info.rx.rx_flags & HTC_RX_PKT_PART_OF_BUNDLE)
2035 			ep->ep_st.rx_bundl += 1;
2036 
2037 		ath6kl_htc_rx_complete(ep, packet);
2038 	}
2039 
2040 	return status;
2041 }
2042 
2043 static int ath6kl_htc_rx_fetch(struct htc_target *target,
2044 			       struct list_head *rx_pktq,
2045 			       struct list_head *comp_pktq)
2046 {
2047 	int fetched_pkts;
2048 	bool part_bundle = false;
2049 	int status = 0;
2050 	struct list_head tmp_rxq;
2051 	struct htc_packet *packet, *tmp_pkt;
2052 
2053 	/* now go fetch the list of HTC packets */
2054 	while (!list_empty(rx_pktq)) {
2055 		fetched_pkts = 0;
2056 
2057 		INIT_LIST_HEAD(&tmp_rxq);
2058 
2059 		if (target->rx_bndl_enable && (get_queue_depth(rx_pktq) > 1)) {
2060 			/*
2061 			 * There are enough packets to attempt a
2062 			 * bundle transfer and recv bundling is
2063 			 * allowed.
2064 			 */
2065 			status = ath6kl_htc_rx_bundle(target, rx_pktq,
2066 						      &tmp_rxq,
2067 						      &fetched_pkts,
2068 						      part_bundle);
2069 			if (status)
2070 				goto fail_rx;
2071 
2072 			if (!list_empty(rx_pktq))
2073 				part_bundle = true;
2074 
2075 			list_splice_tail_init(&tmp_rxq, comp_pktq);
2076 		}
2077 
2078 		if (!fetched_pkts) {
2079 
2080 			packet = list_first_entry(rx_pktq, struct htc_packet,
2081 						   list);
2082 
2083 			/* fully synchronous */
2084 			packet->completion = NULL;
2085 
2086 			if (!list_is_singular(rx_pktq))
2087 				/*
2088 				 * look_aheads in all packet
2089 				 * except the last one in the
2090 				 * bundle must be ignored
2091 				 */
2092 				packet->info.rx.rx_flags |=
2093 					HTC_RX_PKT_IGNORE_LOOKAHEAD;
2094 
2095 			/* go fetch the packet */
2096 			status = ath6kl_htc_rx_packet(target, packet,
2097 						      packet->act_len);
2098 
2099 			list_move_tail(&packet->list, &tmp_rxq);
2100 
2101 			if (status)
2102 				goto fail_rx;
2103 
2104 			list_splice_tail_init(&tmp_rxq, comp_pktq);
2105 		}
2106 	}
2107 
2108 	return 0;
2109 
2110 fail_rx:
2111 
2112 	/*
2113 	 * Cleanup any packets we allocated but didn't use to
2114 	 * actually fetch any packets.
2115 	 */
2116 
2117 	list_for_each_entry_safe(packet, tmp_pkt, rx_pktq, list) {
2118 		list_del(&packet->list);
2119 		htc_reclaim_rxbuf(target, packet,
2120 				  &target->endpoint[packet->endpoint]);
2121 	}
2122 
2123 	list_for_each_entry_safe(packet, tmp_pkt, &tmp_rxq, list) {
2124 		list_del(&packet->list);
2125 		htc_reclaim_rxbuf(target, packet,
2126 				  &target->endpoint[packet->endpoint]);
2127 	}
2128 
2129 	return status;
2130 }
2131 
2132 int ath6kl_htc_rxmsg_pending_handler(struct htc_target *target,
2133 				     u32 msg_look_ahead, int *num_pkts)
2134 {
2135 	struct htc_packet *packets, *tmp_pkt;
2136 	struct htc_endpoint *endpoint;
2137 	struct list_head rx_pktq, comp_pktq;
2138 	int status = 0;
2139 	u32 look_aheads[HTC_HOST_MAX_MSG_PER_BUNDLE];
2140 	int num_look_ahead = 1;
2141 	enum htc_endpoint_id id;
2142 	int n_fetched = 0;
2143 
2144 	INIT_LIST_HEAD(&comp_pktq);
2145 	*num_pkts = 0;
2146 
2147 	/*
2148 	 * On first entry copy the look_aheads into our temp array for
2149 	 * processing
2150 	 */
2151 	look_aheads[0] = msg_look_ahead;
2152 
2153 	while (true) {
2154 
2155 		/*
2156 		 * First lookahead sets the expected endpoint IDs for all
2157 		 * packets in a bundle.
2158 		 */
2159 		id = ((struct htc_frame_hdr *)&look_aheads[0])->eid;
2160 		endpoint = &target->endpoint[id];
2161 
2162 		if (id >= ENDPOINT_MAX) {
2163 			ath6kl_err("MsgPend, invalid endpoint in look-ahead: %d\n",
2164 				   id);
2165 			status = -ENOMEM;
2166 			break;
2167 		}
2168 
2169 		INIT_LIST_HEAD(&rx_pktq);
2170 		INIT_LIST_HEAD(&comp_pktq);
2171 
2172 		/*
2173 		 * Try to allocate as many HTC RX packets indicated by the
2174 		 * look_aheads.
2175 		 */
2176 		status = ath6kl_htc_rx_alloc(target, look_aheads,
2177 					     num_look_ahead, endpoint,
2178 					     &rx_pktq);
2179 		if (status)
2180 			break;
2181 
2182 		if (get_queue_depth(&rx_pktq) >= 2)
2183 			/*
2184 			 * A recv bundle was detected, force IRQ status
2185 			 * re-check again
2186 			 */
2187 			target->chk_irq_status_cnt = 1;
2188 
2189 		n_fetched += get_queue_depth(&rx_pktq);
2190 
2191 		num_look_ahead = 0;
2192 
2193 		status = ath6kl_htc_rx_fetch(target, &rx_pktq, &comp_pktq);
2194 
2195 		if (!status)
2196 			ath6kl_htc_rx_chk_water_mark(endpoint);
2197 
2198 		/* Process fetched packets */
2199 		status = ath6kl_htc_rx_process_packets(target, &comp_pktq,
2200 						       look_aheads,
2201 						       &num_look_ahead);
2202 
2203 		if (!num_look_ahead || status)
2204 			break;
2205 
2206 		/*
2207 		 * For SYNCH processing, if we get here, we are running
2208 		 * through the loop again due to a detected lookahead. Set
2209 		 * flag that we should re-check IRQ status registers again
2210 		 * before leaving IRQ processing, this can net better
2211 		 * performance in high throughput situations.
2212 		 */
2213 		target->chk_irq_status_cnt = 1;
2214 	}
2215 
2216 	if (status) {
2217 		ath6kl_err("failed to get pending recv messages: %d\n",
2218 			   status);
2219 
2220 		/* cleanup any packets in sync completion queue */
2221 		list_for_each_entry_safe(packets, tmp_pkt, &comp_pktq, list) {
2222 			list_del(&packets->list);
2223 			htc_reclaim_rxbuf(target, packets,
2224 					  &target->endpoint[packets->endpoint]);
2225 		}
2226 
2227 		if (target->htc_flags & HTC_OP_STATE_STOPPING) {
2228 			ath6kl_warn("host is going to stop blocking receiver for htc_stop\n");
2229 			ath6kl_hif_rx_control(target->dev, false);
2230 		}
2231 	}
2232 
2233 	/*
2234 	 * Before leaving, check to see if host ran out of buffers and
2235 	 * needs to stop the receiver.
2236 	 */
2237 	if (target->rx_st_flags & HTC_RECV_WAIT_BUFFERS) {
2238 		ath6kl_warn("host has no rx buffers blocking receiver to prevent overrun\n");
2239 		ath6kl_hif_rx_control(target->dev, false);
2240 	}
2241 	*num_pkts = n_fetched;
2242 
2243 	return status;
2244 }
2245 
2246 /*
2247  * Synchronously wait for a control message from the target,
2248  * This function is used at initialization time ONLY.  At init messages
2249  * on ENDPOINT 0 are expected.
2250  */
2251 static struct htc_packet *htc_wait_for_ctrl_msg(struct htc_target *target)
2252 {
2253 	struct htc_packet *packet = NULL;
2254 	struct htc_frame_hdr *htc_hdr;
2255 	u32 look_ahead;
2256 
2257 	if (ath6kl_hif_poll_mboxmsg_rx(target->dev, &look_ahead,
2258 				       HTC_TARGET_RESPONSE_TIMEOUT))
2259 		return NULL;
2260 
2261 	ath6kl_dbg(ATH6KL_DBG_HTC,
2262 		   "htc rx wait ctrl look_ahead 0x%X\n", look_ahead);
2263 
2264 	htc_hdr = (struct htc_frame_hdr *)&look_ahead;
2265 
2266 	if (htc_hdr->eid != ENDPOINT_0)
2267 		return NULL;
2268 
2269 	packet = htc_get_control_buf(target, false);
2270 
2271 	if (!packet)
2272 		return NULL;
2273 
2274 	packet->info.rx.rx_flags = 0;
2275 	packet->info.rx.exp_hdr = look_ahead;
2276 	packet->act_len = le16_to_cpu(htc_hdr->payld_len) + HTC_HDR_LENGTH;
2277 
2278 	if (packet->act_len > packet->buf_len)
2279 		goto fail_ctrl_rx;
2280 
2281 	/* we want synchronous operation */
2282 	packet->completion = NULL;
2283 
2284 	/* get the message from the device, this will block */
2285 	if (ath6kl_htc_rx_packet(target, packet, packet->act_len))
2286 		goto fail_ctrl_rx;
2287 
2288 	/* process receive header */
2289 	packet->status = ath6kl_htc_rx_process_hdr(target, packet, NULL, NULL);
2290 
2291 	if (packet->status) {
2292 		ath6kl_err("htc_wait_for_ctrl_msg, ath6kl_htc_rx_process_hdr failed (status = %d)\n",
2293 			   packet->status);
2294 		goto fail_ctrl_rx;
2295 	}
2296 
2297 	return packet;
2298 
2299 fail_ctrl_rx:
2300 	if (packet != NULL) {
2301 		htc_rxpkt_reset(packet);
2302 		reclaim_rx_ctrl_buf(target, packet);
2303 	}
2304 
2305 	return NULL;
2306 }
2307 
2308 static int ath6kl_htc_mbox_add_rxbuf_multiple(struct htc_target *target,
2309 				  struct list_head *pkt_queue)
2310 {
2311 	struct htc_endpoint *endpoint;
2312 	struct htc_packet *first_pkt;
2313 	bool rx_unblock = false;
2314 	int status = 0, depth;
2315 
2316 	if (list_empty(pkt_queue))
2317 		return -ENOMEM;
2318 
2319 	first_pkt = list_first_entry(pkt_queue, struct htc_packet, list);
2320 
2321 	if (first_pkt->endpoint >= ENDPOINT_MAX)
2322 		return status;
2323 
2324 	depth = get_queue_depth(pkt_queue);
2325 
2326 	ath6kl_dbg(ATH6KL_DBG_HTC,
2327 		   "htc rx add multiple ep id %d cnt %d len %d\n",
2328 		first_pkt->endpoint, depth, first_pkt->buf_len);
2329 
2330 	endpoint = &target->endpoint[first_pkt->endpoint];
2331 
2332 	if (target->htc_flags & HTC_OP_STATE_STOPPING) {
2333 		struct htc_packet *packet, *tmp_pkt;
2334 
2335 		/* walk through queue and mark each one canceled */
2336 		list_for_each_entry_safe(packet, tmp_pkt, pkt_queue, list) {
2337 			packet->status = -ECANCELED;
2338 			list_del(&packet->list);
2339 			ath6kl_htc_rx_complete(endpoint, packet);
2340 		}
2341 
2342 		return status;
2343 	}
2344 
2345 	spin_lock_bh(&target->rx_lock);
2346 
2347 	list_splice_tail_init(pkt_queue, &endpoint->rx_bufq);
2348 
2349 	/* check if we are blocked waiting for a new buffer */
2350 	if (target->rx_st_flags & HTC_RECV_WAIT_BUFFERS) {
2351 		if (target->ep_waiting == first_pkt->endpoint) {
2352 			ath6kl_dbg(ATH6KL_DBG_HTC,
2353 				   "htc rx blocked on ep %d, unblocking\n",
2354 				   target->ep_waiting);
2355 			target->rx_st_flags &= ~HTC_RECV_WAIT_BUFFERS;
2356 			target->ep_waiting = ENDPOINT_MAX;
2357 			rx_unblock = true;
2358 		}
2359 	}
2360 
2361 	spin_unlock_bh(&target->rx_lock);
2362 
2363 	if (rx_unblock && !(target->htc_flags & HTC_OP_STATE_STOPPING))
2364 		/* TODO : implement a buffer threshold count? */
2365 		ath6kl_hif_rx_control(target->dev, true);
2366 
2367 	return status;
2368 }
2369 
2370 static void ath6kl_htc_mbox_flush_rx_buf(struct htc_target *target)
2371 {
2372 	struct htc_endpoint *endpoint;
2373 	struct htc_packet *packet, *tmp_pkt;
2374 	int i;
2375 
2376 	for (i = ENDPOINT_0; i < ENDPOINT_MAX; i++) {
2377 		endpoint = &target->endpoint[i];
2378 		if (!endpoint->svc_id)
2379 			/* not in use.. */
2380 			continue;
2381 
2382 		spin_lock_bh(&target->rx_lock);
2383 		list_for_each_entry_safe(packet, tmp_pkt,
2384 					 &endpoint->rx_bufq, list) {
2385 			list_del(&packet->list);
2386 			spin_unlock_bh(&target->rx_lock);
2387 			ath6kl_dbg(ATH6KL_DBG_HTC,
2388 				   "htc rx flush pkt 0x%p  len %d  ep %d\n",
2389 				   packet, packet->buf_len,
2390 				   packet->endpoint);
2391 			/*
2392 			 * packets in rx_bufq of endpoint 0 have originally
2393 			 * been queued from target->free_ctrl_rxbuf where
2394 			 * packet and packet->buf_start are allocated
2395 			 * separately using kmalloc(). For other endpoint
2396 			 * rx_bufq, it is allocated as skb where packet is
2397 			 * skb->head. Take care of this difference while freeing
2398 			 * the memory.
2399 			 */
2400 			if (packet->endpoint == ENDPOINT_0) {
2401 				kfree(packet->buf_start);
2402 				kfree(packet);
2403 			} else {
2404 				dev_kfree_skb(packet->pkt_cntxt);
2405 			}
2406 			spin_lock_bh(&target->rx_lock);
2407 		}
2408 		spin_unlock_bh(&target->rx_lock);
2409 	}
2410 }
2411 
2412 static int ath6kl_htc_mbox_conn_service(struct htc_target *target,
2413 			    struct htc_service_connect_req *conn_req,
2414 			    struct htc_service_connect_resp *conn_resp)
2415 {
2416 	struct htc_packet *rx_pkt = NULL;
2417 	struct htc_packet *tx_pkt = NULL;
2418 	struct htc_conn_service_resp *resp_msg;
2419 	struct htc_conn_service_msg *conn_msg;
2420 	struct htc_endpoint *endpoint;
2421 	enum htc_endpoint_id assigned_ep = ENDPOINT_MAX;
2422 	unsigned int max_msg_sz = 0;
2423 	int status = 0;
2424 	u16 msg_id;
2425 
2426 	ath6kl_dbg(ATH6KL_DBG_HTC,
2427 		   "htc connect service target 0x%p service id 0x%x\n",
2428 		   target, conn_req->svc_id);
2429 
2430 	if (conn_req->svc_id == HTC_CTRL_RSVD_SVC) {
2431 		/* special case for pseudo control service */
2432 		assigned_ep = ENDPOINT_0;
2433 		max_msg_sz = HTC_MAX_CTRL_MSG_LEN;
2434 	} else {
2435 		/* allocate a packet to send to the target */
2436 		tx_pkt = htc_get_control_buf(target, true);
2437 
2438 		if (!tx_pkt)
2439 			return -ENOMEM;
2440 
2441 		conn_msg = (struct htc_conn_service_msg *)tx_pkt->buf;
2442 		memset(conn_msg, 0, sizeof(*conn_msg));
2443 		conn_msg->msg_id = cpu_to_le16(HTC_MSG_CONN_SVC_ID);
2444 		conn_msg->svc_id = cpu_to_le16(conn_req->svc_id);
2445 		conn_msg->conn_flags = cpu_to_le16(conn_req->conn_flags);
2446 
2447 		set_htc_pkt_info(tx_pkt, NULL, (u8 *) conn_msg,
2448 				 sizeof(*conn_msg) + conn_msg->svc_meta_len,
2449 				 ENDPOINT_0, HTC_SERVICE_TX_PACKET_TAG);
2450 
2451 		/* we want synchronous operation */
2452 		tx_pkt->completion = NULL;
2453 		ath6kl_htc_tx_prep_pkt(tx_pkt, 0, 0, 0);
2454 		status = ath6kl_htc_tx_issue(target, tx_pkt);
2455 
2456 		if (status)
2457 			goto fail_tx;
2458 
2459 		/* wait for response */
2460 		rx_pkt = htc_wait_for_ctrl_msg(target);
2461 
2462 		if (!rx_pkt) {
2463 			status = -ENOMEM;
2464 			goto fail_tx;
2465 		}
2466 
2467 		resp_msg = (struct htc_conn_service_resp *)rx_pkt->buf;
2468 		msg_id = le16_to_cpu(resp_msg->msg_id);
2469 
2470 		if ((msg_id != HTC_MSG_CONN_SVC_RESP_ID) ||
2471 		    (rx_pkt->act_len < sizeof(*resp_msg))) {
2472 			status = -ENOMEM;
2473 			goto fail_tx;
2474 		}
2475 
2476 		conn_resp->resp_code = resp_msg->status;
2477 		/* check response status */
2478 		if (resp_msg->status != HTC_SERVICE_SUCCESS) {
2479 			ath6kl_err("target failed service 0x%X connect request (status:%d)\n",
2480 				   resp_msg->svc_id, resp_msg->status);
2481 			status = -ENOMEM;
2482 			goto fail_tx;
2483 		}
2484 
2485 		assigned_ep = (enum htc_endpoint_id)resp_msg->eid;
2486 		max_msg_sz = le16_to_cpu(resp_msg->max_msg_sz);
2487 	}
2488 
2489 	if (assigned_ep >= ENDPOINT_MAX || !max_msg_sz) {
2490 		status = -ENOMEM;
2491 		goto fail_tx;
2492 	}
2493 
2494 	endpoint = &target->endpoint[assigned_ep];
2495 	endpoint->eid = assigned_ep;
2496 	if (endpoint->svc_id) {
2497 		status = -ENOMEM;
2498 		goto fail_tx;
2499 	}
2500 
2501 	/* return assigned endpoint to caller */
2502 	conn_resp->endpoint = assigned_ep;
2503 	conn_resp->len_max = max_msg_sz;
2504 
2505 	/* setup the endpoint */
2506 
2507 	/* this marks the endpoint in use */
2508 	endpoint->svc_id = conn_req->svc_id;
2509 
2510 	endpoint->max_txq_depth = conn_req->max_txq_depth;
2511 	endpoint->len_max = max_msg_sz;
2512 	endpoint->ep_cb = conn_req->ep_cb;
2513 	endpoint->cred_dist.svc_id = conn_req->svc_id;
2514 	endpoint->cred_dist.htc_ep = endpoint;
2515 	endpoint->cred_dist.endpoint = assigned_ep;
2516 	endpoint->cred_dist.cred_sz = target->tgt_cred_sz;
2517 
2518 	switch (endpoint->svc_id) {
2519 	case WMI_DATA_BK_SVC:
2520 		endpoint->tx_drop_packet_threshold = MAX_DEF_COOKIE_NUM / 3;
2521 		break;
2522 	default:
2523 		endpoint->tx_drop_packet_threshold = MAX_HI_COOKIE_NUM;
2524 		break;
2525 	}
2526 
2527 	if (conn_req->max_rxmsg_sz) {
2528 		/*
2529 		 * Override cred_per_msg calculation, this optimizes
2530 		 * the credit-low indications since the host will actually
2531 		 * issue smaller messages in the Send path.
2532 		 */
2533 		if (conn_req->max_rxmsg_sz > max_msg_sz) {
2534 			status = -ENOMEM;
2535 			goto fail_tx;
2536 		}
2537 		endpoint->cred_dist.cred_per_msg =
2538 		    conn_req->max_rxmsg_sz / target->tgt_cred_sz;
2539 	} else
2540 		endpoint->cred_dist.cred_per_msg =
2541 		    max_msg_sz / target->tgt_cred_sz;
2542 
2543 	if (!endpoint->cred_dist.cred_per_msg)
2544 		endpoint->cred_dist.cred_per_msg = 1;
2545 
2546 	/* save local connection flags */
2547 	endpoint->conn_flags = conn_req->flags;
2548 
2549 fail_tx:
2550 	if (tx_pkt)
2551 		htc_reclaim_txctrl_buf(target, tx_pkt);
2552 
2553 	if (rx_pkt) {
2554 		htc_rxpkt_reset(rx_pkt);
2555 		reclaim_rx_ctrl_buf(target, rx_pkt);
2556 	}
2557 
2558 	return status;
2559 }
2560 
2561 static void reset_ep_state(struct htc_target *target)
2562 {
2563 	struct htc_endpoint *endpoint;
2564 	int i;
2565 
2566 	for (i = ENDPOINT_0; i < ENDPOINT_MAX; i++) {
2567 		endpoint = &target->endpoint[i];
2568 		memset(&endpoint->cred_dist, 0, sizeof(endpoint->cred_dist));
2569 		endpoint->svc_id = 0;
2570 		endpoint->len_max = 0;
2571 		endpoint->max_txq_depth = 0;
2572 		memset(&endpoint->ep_st, 0,
2573 		       sizeof(endpoint->ep_st));
2574 		INIT_LIST_HEAD(&endpoint->rx_bufq);
2575 		INIT_LIST_HEAD(&endpoint->txq);
2576 		endpoint->target = target;
2577 	}
2578 
2579 	/* reset distribution list */
2580 	/* FIXME: free existing entries */
2581 	INIT_LIST_HEAD(&target->cred_dist_list);
2582 }
2583 
2584 static int ath6kl_htc_mbox_get_rxbuf_num(struct htc_target *target,
2585 			     enum htc_endpoint_id endpoint)
2586 {
2587 	int num;
2588 
2589 	spin_lock_bh(&target->rx_lock);
2590 	num = get_queue_depth(&(target->endpoint[endpoint].rx_bufq));
2591 	spin_unlock_bh(&target->rx_lock);
2592 	return num;
2593 }
2594 
2595 static void htc_setup_msg_bndl(struct htc_target *target)
2596 {
2597 	/* limit what HTC can handle */
2598 	target->msg_per_bndl_max = min(HTC_HOST_MAX_MSG_PER_BUNDLE,
2599 				       target->msg_per_bndl_max);
2600 
2601 	if (ath6kl_hif_enable_scatter(target->dev->ar)) {
2602 		target->msg_per_bndl_max = 0;
2603 		return;
2604 	}
2605 
2606 	/* limit bundle what the device layer can handle */
2607 	target->msg_per_bndl_max = min(target->max_scat_entries,
2608 				       target->msg_per_bndl_max);
2609 
2610 	ath6kl_dbg(ATH6KL_DBG_BOOT,
2611 		   "htc bundling allowed msg_per_bndl_max %d\n",
2612 		   target->msg_per_bndl_max);
2613 
2614 	/* Max rx bundle size is limited by the max tx bundle size */
2615 	target->max_rx_bndl_sz = target->max_xfer_szper_scatreq;
2616 	/* Max tx bundle size if limited by the extended mbox address range */
2617 	target->max_tx_bndl_sz = min(HIF_MBOX0_EXT_WIDTH,
2618 				     target->max_xfer_szper_scatreq);
2619 
2620 	ath6kl_dbg(ATH6KL_DBG_BOOT, "htc max_rx_bndl_sz %d max_tx_bndl_sz %d\n",
2621 		   target->max_rx_bndl_sz, target->max_tx_bndl_sz);
2622 
2623 	if (target->max_tx_bndl_sz)
2624 		/* tx_bndl_mask is enabled per AC, each has 1 bit */
2625 		target->tx_bndl_mask = (1 << WMM_NUM_AC) - 1;
2626 
2627 	if (target->max_rx_bndl_sz)
2628 		target->rx_bndl_enable = true;
2629 
2630 	if ((target->tgt_cred_sz % target->block_sz) != 0) {
2631 		ath6kl_warn("credit size: %d is not block aligned! Disabling send bundling\n",
2632 			    target->tgt_cred_sz);
2633 
2634 		/*
2635 		 * Disallow send bundling since the credit size is
2636 		 * not aligned to a block size the I/O block
2637 		 * padding will spill into the next credit buffer
2638 		 * which is fatal.
2639 		 */
2640 		target->tx_bndl_mask = 0;
2641 	}
2642 }
2643 
2644 static int ath6kl_htc_mbox_wait_target(struct htc_target *target)
2645 {
2646 	struct htc_packet *packet = NULL;
2647 	struct htc_ready_ext_msg *rdy_msg;
2648 	struct htc_service_connect_req connect;
2649 	struct htc_service_connect_resp resp;
2650 	int status;
2651 
2652 	/* FIXME: remove once USB support is implemented */
2653 	if (target->dev->ar->hif_type == ATH6KL_HIF_TYPE_USB) {
2654 		ath6kl_err("HTC doesn't support USB yet. Patience!\n");
2655 		return -EOPNOTSUPP;
2656 	}
2657 
2658 	/* we should be getting 1 control message that the target is ready */
2659 	packet = htc_wait_for_ctrl_msg(target);
2660 
2661 	if (!packet)
2662 		return -ENOMEM;
2663 
2664 	/* we controlled the buffer creation so it's properly aligned */
2665 	rdy_msg = (struct htc_ready_ext_msg *)packet->buf;
2666 
2667 	if ((le16_to_cpu(rdy_msg->ver2_0_info.msg_id) != HTC_MSG_READY_ID) ||
2668 	    (packet->act_len < sizeof(struct htc_ready_msg))) {
2669 		status = -ENOMEM;
2670 		goto fail_wait_target;
2671 	}
2672 
2673 	if (!rdy_msg->ver2_0_info.cred_cnt || !rdy_msg->ver2_0_info.cred_sz) {
2674 		status = -ENOMEM;
2675 		goto fail_wait_target;
2676 	}
2677 
2678 	target->tgt_creds = le16_to_cpu(rdy_msg->ver2_0_info.cred_cnt);
2679 	target->tgt_cred_sz = le16_to_cpu(rdy_msg->ver2_0_info.cred_sz);
2680 
2681 	ath6kl_dbg(ATH6KL_DBG_BOOT,
2682 		   "htc target ready credits %d size %d\n",
2683 		   target->tgt_creds, target->tgt_cred_sz);
2684 
2685 	/* check if this is an extended ready message */
2686 	if (packet->act_len >= sizeof(struct htc_ready_ext_msg)) {
2687 		/* this is an extended message */
2688 		target->htc_tgt_ver = rdy_msg->htc_ver;
2689 		target->msg_per_bndl_max = rdy_msg->msg_per_htc_bndl;
2690 	} else {
2691 		/* legacy */
2692 		target->htc_tgt_ver = HTC_VERSION_2P0;
2693 		target->msg_per_bndl_max = 0;
2694 	}
2695 
2696 	ath6kl_dbg(ATH6KL_DBG_BOOT, "htc using protocol %s (%d)\n",
2697 		   (target->htc_tgt_ver == HTC_VERSION_2P0) ? "2.0" : ">= 2.1",
2698 		   target->htc_tgt_ver);
2699 
2700 	if (target->msg_per_bndl_max > 0)
2701 		htc_setup_msg_bndl(target);
2702 
2703 	/* setup our pseudo HTC control endpoint connection */
2704 	memset(&connect, 0, sizeof(connect));
2705 	memset(&resp, 0, sizeof(resp));
2706 	connect.ep_cb.rx = htc_ctrl_rx;
2707 	connect.ep_cb.rx_refill = NULL;
2708 	connect.ep_cb.tx_full = NULL;
2709 	connect.max_txq_depth = NUM_CONTROL_BUFFERS;
2710 	connect.svc_id = HTC_CTRL_RSVD_SVC;
2711 
2712 	/* connect fake service */
2713 	status = ath6kl_htc_mbox_conn_service((void *)target, &connect, &resp);
2714 
2715 	if (status)
2716 		/*
2717 		 * FIXME: this call doesn't make sense, the caller should
2718 		 * call ath6kl_htc_mbox_cleanup() when it wants remove htc
2719 		 */
2720 		ath6kl_hif_cleanup_scatter(target->dev->ar);
2721 
2722 fail_wait_target:
2723 	if (packet) {
2724 		htc_rxpkt_reset(packet);
2725 		reclaim_rx_ctrl_buf(target, packet);
2726 	}
2727 
2728 	return status;
2729 }
2730 
2731 /*
2732  * Start HTC, enable interrupts and let the target know
2733  * host has finished setup.
2734  */
2735 static int ath6kl_htc_mbox_start(struct htc_target *target)
2736 {
2737 	struct htc_packet *packet;
2738 	int status;
2739 
2740 	memset(&target->dev->irq_proc_reg, 0,
2741 	       sizeof(target->dev->irq_proc_reg));
2742 
2743 	/* Disable interrupts at the chip level */
2744 	ath6kl_hif_disable_intrs(target->dev);
2745 
2746 	target->htc_flags = 0;
2747 	target->rx_st_flags = 0;
2748 
2749 	/* Push control receive buffers into htc control endpoint */
2750 	while ((packet = htc_get_control_buf(target, false)) != NULL) {
2751 		status = htc_add_rxbuf(target, packet);
2752 		if (status)
2753 			return status;
2754 	}
2755 
2756 	/* NOTE: the first entry in the distribution list is ENDPOINT_0 */
2757 	ath6kl_credit_init(target->credit_info, &target->cred_dist_list,
2758 			   target->tgt_creds);
2759 
2760 	dump_cred_dist_stats(target);
2761 
2762 	/* Indicate to the target of the setup completion */
2763 	status = htc_setup_tx_complete(target);
2764 
2765 	if (status)
2766 		return status;
2767 
2768 	/* unmask interrupts */
2769 	status = ath6kl_hif_unmask_intrs(target->dev);
2770 
2771 	if (status)
2772 		ath6kl_htc_mbox_stop(target);
2773 
2774 	return status;
2775 }
2776 
2777 static int ath6kl_htc_reset(struct htc_target *target)
2778 {
2779 	u32 block_size, ctrl_bufsz;
2780 	struct htc_packet *packet;
2781 	int i;
2782 
2783 	reset_ep_state(target);
2784 
2785 	block_size = target->dev->ar->mbox_info.block_size;
2786 
2787 	ctrl_bufsz = (block_size > HTC_MAX_CTRL_MSG_LEN) ?
2788 		      (block_size + HTC_HDR_LENGTH) :
2789 		      (HTC_MAX_CTRL_MSG_LEN + HTC_HDR_LENGTH);
2790 
2791 	for (i = 0; i < NUM_CONTROL_BUFFERS; i++) {
2792 		packet = kzalloc(sizeof(*packet), GFP_KERNEL);
2793 		if (!packet)
2794 			return -ENOMEM;
2795 
2796 		packet->buf_start = kzalloc(ctrl_bufsz, GFP_KERNEL);
2797 		if (!packet->buf_start) {
2798 			kfree(packet);
2799 			return -ENOMEM;
2800 		}
2801 
2802 		packet->buf_len = ctrl_bufsz;
2803 		if (i < NUM_CONTROL_RX_BUFFERS) {
2804 			packet->act_len = 0;
2805 			packet->buf = packet->buf_start;
2806 			packet->endpoint = ENDPOINT_0;
2807 			list_add_tail(&packet->list, &target->free_ctrl_rxbuf);
2808 		} else
2809 			list_add_tail(&packet->list, &target->free_ctrl_txbuf);
2810 	}
2811 
2812 	return 0;
2813 }
2814 
2815 /* htc_stop: stop interrupt reception, and flush all queued buffers */
2816 static void ath6kl_htc_mbox_stop(struct htc_target *target)
2817 {
2818 	spin_lock_bh(&target->htc_lock);
2819 	target->htc_flags |= HTC_OP_STATE_STOPPING;
2820 	spin_unlock_bh(&target->htc_lock);
2821 
2822 	/*
2823 	 * Masking interrupts is a synchronous operation, when this
2824 	 * function returns all pending HIF I/O has completed, we can
2825 	 * safely flush the queues.
2826 	 */
2827 	ath6kl_hif_mask_intrs(target->dev);
2828 
2829 	ath6kl_htc_flush_txep_all(target);
2830 
2831 	ath6kl_htc_mbox_flush_rx_buf(target);
2832 
2833 	ath6kl_htc_reset(target);
2834 }
2835 
2836 static void *ath6kl_htc_mbox_create(struct ath6kl *ar)
2837 {
2838 	struct htc_target *target = NULL;
2839 	int status = 0;
2840 
2841 	target = kzalloc(sizeof(*target), GFP_KERNEL);
2842 	if (!target) {
2843 		ath6kl_err("unable to allocate memory\n");
2844 		return NULL;
2845 	}
2846 
2847 	target->dev = kzalloc(sizeof(*target->dev), GFP_KERNEL);
2848 	if (!target->dev) {
2849 		ath6kl_err("unable to allocate memory\n");
2850 		status = -ENOMEM;
2851 		goto err_htc_cleanup;
2852 	}
2853 
2854 	spin_lock_init(&target->htc_lock);
2855 	spin_lock_init(&target->rx_lock);
2856 	spin_lock_init(&target->tx_lock);
2857 
2858 	INIT_LIST_HEAD(&target->free_ctrl_txbuf);
2859 	INIT_LIST_HEAD(&target->free_ctrl_rxbuf);
2860 	INIT_LIST_HEAD(&target->cred_dist_list);
2861 
2862 	target->dev->ar = ar;
2863 	target->dev->htc_cnxt = target;
2864 	target->ep_waiting = ENDPOINT_MAX;
2865 
2866 	status = ath6kl_hif_setup(target->dev);
2867 	if (status)
2868 		goto err_htc_cleanup;
2869 
2870 	status = ath6kl_htc_reset(target);
2871 	if (status)
2872 		goto err_htc_cleanup;
2873 
2874 	return target;
2875 
2876 err_htc_cleanup:
2877 	ath6kl_htc_mbox_cleanup(target);
2878 
2879 	return NULL;
2880 }
2881 
2882 /* cleanup the HTC instance */
2883 static void ath6kl_htc_mbox_cleanup(struct htc_target *target)
2884 {
2885 	struct htc_packet *packet, *tmp_packet;
2886 
2887 	/* FIXME: remove check once USB support is implemented */
2888 	if (target->dev->ar->hif_type != ATH6KL_HIF_TYPE_USB)
2889 		ath6kl_hif_cleanup_scatter(target->dev->ar);
2890 
2891 	list_for_each_entry_safe(packet, tmp_packet,
2892 				 &target->free_ctrl_txbuf, list) {
2893 		list_del(&packet->list);
2894 		kfree(packet->buf_start);
2895 		kfree(packet);
2896 	}
2897 
2898 	list_for_each_entry_safe(packet, tmp_packet,
2899 				 &target->free_ctrl_rxbuf, list) {
2900 		list_del(&packet->list);
2901 		kfree(packet->buf_start);
2902 		kfree(packet);
2903 	}
2904 
2905 	kfree(target->dev);
2906 	kfree(target);
2907 }
2908 
2909 static const struct ath6kl_htc_ops ath6kl_htc_mbox_ops = {
2910 	.create = ath6kl_htc_mbox_create,
2911 	.wait_target = ath6kl_htc_mbox_wait_target,
2912 	.start = ath6kl_htc_mbox_start,
2913 	.conn_service = ath6kl_htc_mbox_conn_service,
2914 	.tx = ath6kl_htc_mbox_tx,
2915 	.stop = ath6kl_htc_mbox_stop,
2916 	.cleanup = ath6kl_htc_mbox_cleanup,
2917 	.flush_txep = ath6kl_htc_mbox_flush_txep,
2918 	.flush_rx_buf = ath6kl_htc_mbox_flush_rx_buf,
2919 	.activity_changed = ath6kl_htc_mbox_activity_changed,
2920 	.get_rxbuf_num = ath6kl_htc_mbox_get_rxbuf_num,
2921 	.add_rxbuf_multiple = ath6kl_htc_mbox_add_rxbuf_multiple,
2922 	.credit_setup = ath6kl_htc_mbox_credit_setup,
2923 };
2924 
2925 void ath6kl_htc_mbox_attach(struct ath6kl *ar)
2926 {
2927 	ar->htc_ops = &ath6kl_htc_mbox_ops;
2928 }
2929