static int userfaultfd_register(struct userfaultfd_ctx *ctx,
				unsigned long arg)
{
	struct mm_struct *mm = ctx->mm;
	struct vm_area_struct *vma, *prev, *cur;
	int ret;
	struct uffdio_register uffdio_register;
	struct uffdio_register __user *user_uffdio_register;
	unsigned long vm_flags, new_flags;
	bool found;
	bool basic_ioctls;
	unsigned long start, end, vma_end;

	user_uffdio_register = (struct uffdio_register __user *) arg;

	ret = -EFAULT;
	if (copy_from_user(&uffdio_register, user_uffdio_register,
			   sizeof(uffdio_register)-sizeof(__u64)))
		goto out;

	ret = -EINVAL;
	if (!uffdio_register.mode)
		goto out;
	if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
				     UFFDIO_REGISTER_MODE_WP))
		goto out;
	vm_flags = 0;
	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
		vm_flags |= VM_UFFD_MISSING;
	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
		vm_flags |= VM_UFFD_WP;
		/*
		 * FIXME: remove the below error constraint by
		 * implementing the wprotect tracking mode.
		 */
		ret = -EINVAL;
		goto out;
	}

	ret = validate_range(mm, uffdio_register.range.start,
			     uffdio_register.range.len);
	if (ret)
		goto out;

	start = uffdio_register.range.start;
	end = start + uffdio_register.range.len;

	ret = -ENOMEM;
	if (!mmget_not_zero(mm))
		goto out;

	down_write(&mm->mmap_sem);
	if (!mmget_still_valid(mm))
		goto out_unlock;
	vma = find_vma_prev(mm, start, &prev);
	if (!vma)
		goto out_unlock;

	/* check that there's at least one vma in the range */
	ret = -EINVAL;
	if (vma->vm_start >= end)
		goto out_unlock;

	/*
	 * If the first vma contains huge pages, make sure start address
	 * is aligned to huge page size.
	 */
	if (is_vm_hugetlb_page(vma)) {
		unsigned long vma_hpagesize = vma_kernel_pagesize(vma);

		if (start & (vma_hpagesize - 1))
			goto out_unlock;
	}

	/*
	 * Search for not compatible vmas.
	 */
	found = false;
	basic_ioctls = false;
	for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
		cond_resched();

		BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
		       !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));

		/* check not compatible vmas */
		ret = -EINVAL;
		if (!vma_can_userfault(cur))
			goto out_unlock;

		/*
		 * UFFDIO_COPY will fill file holes even without
		 * PROT_WRITE. This check enforces that if this is a
		 * MAP_SHARED, the process has write permission to the backing
		 * file. If VM_MAYWRITE is set it also enforces that on a
		 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
		 * F_WRITE_SEAL can be taken until the vma is destroyed.
		 */
		ret = -EPERM;
		if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
			goto out_unlock;

		/*
		 * If this vma contains ending address, and huge pages
		 * check alignment.
		 */
		if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
		    end > cur->vm_start) {
			unsigned long vma_hpagesize = vma_kernel_pagesize(cur);

			ret = -EINVAL;

			if (end & (vma_hpagesize - 1))
				goto out_unlock;
		}

		/*
		 * Check that this vma isn't already owned by a
		 * different userfaultfd. We can't allow more than one
		 * userfaultfd to own a single vma simultaneously or we
		 * wouldn't know which one to deliver the userfaults to.
		 */
		ret = -EBUSY;
		if (cur->vm_userfaultfd_ctx.ctx &&
		    cur->vm_userfaultfd_ctx.ctx != ctx)
			goto out_unlock;

		/*
		 * Note vmas containing huge pages
		 */
		if (is_vm_hugetlb_page(cur))
			basic_ioctls = true;

		found = true;
	}
	BUG_ON(!found);

	if (vma->vm_start < start)
		prev = vma;

	ret = 0;
	do {
		cond_resched();

		BUG_ON(!vma_can_userfault(vma));
		BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
		       vma->vm_userfaultfd_ctx.ctx != ctx);
		WARN_ON(!(vma->vm_flags & VM_MAYWRITE));

		/*
		 * Nothing to do: this vma is already registered into this
		 * userfaultfd and with the right tracking mode too.
		 */
		if (vma->vm_userfaultfd_ctx.ctx == ctx &&
		    (vma->vm_flags & vm_flags) == vm_flags)
			goto skip;

		if (vma->vm_start > start)
			start = vma->vm_start;
		vma_end = min(end, vma->vm_end);

		new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
		prev = vma_merge(mm, prev, start, vma_end, new_flags,
				 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
				 vma_policy(vma),
				 ((struct vm_userfaultfd_ctx){ ctx }));
		if (prev) {
			vma = prev;
			goto next;
		}
		if (vma->vm_start < start) {
			ret = split_vma(mm, vma, start, 1);
			if (ret)
				break;
		}
		if (vma->vm_end > end) {
			ret = split_vma(mm, vma, end, 0);
			if (ret)
				break;
		}
	next:
		/*
		 * In the vma_merge() successful mprotect-like case 8:
		 * the next vma was merged into the current one and
		 * the current one has not been updated yet.
		 */
		vma->vm_flags = new_flags;
		vma->vm_userfaultfd_ctx.ctx = ctx;

	skip:
		prev = vma;
		start = vma->vm_end;
		vma = vma->vm_next;
	} while (vma && vma->vm_start < end);
out_unlock:
	up_write(&mm->mmap_sem);
	mmput(mm);
	if (!ret) {
		/*
		 * Now that we scanned all vmas we can already tell
		 * userland which ioctls methods are guaranteed to
		 * succeed on this range.
		 */
		if (put_user(basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
			     UFFD_API_RANGE_IOCTLS,
			     &user_uffdio_register->ioctls))
			ret = -EFAULT;
	}
out:
	return ret;
}


static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
{
	struct inode *inode = fdentry(file)->d_inode;
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_root *new_root;
	struct btrfs_dir_item *di;
	struct btrfs_trans_handle *trans;
	struct btrfs_path *path;
	struct btrfs_key location;
	struct btrfs_disk_key disk_key;
	u64 objectid = 0;
	u64 dir_id;
	int ret;

	if (!capable(CAP_SYS_ADMIN))
		return -EPERM;

	ret = mnt_want_write_file(file);
	if (ret)
		return ret;

	if (copy_from_user(&objectid, argp, sizeof(objectid))) {
		ret = -EFAULT;
		goto out;
	}

	if (!objectid)
		objectid = root->root_key.objectid;

	location.objectid = objectid;
	location.type = BTRFS_ROOT_ITEM_KEY;
	location.offset = (u64)-1;

	new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
	if (IS_ERR(new_root)) {
		ret = PTR_ERR(new_root);
		goto out;
	}

	if (btrfs_root_refs(&new_root->root_item) == 0) {
		ret = -ENOENT;
		goto out;
	}

	path = btrfs_alloc_path();
	if (!path) {
		ret = -ENOMEM;
		goto out;
	}
	path->leave_spinning = 1;

	trans = btrfs_start_transaction(root, 1);
	if (IS_ERR(trans)) {
		btrfs_free_path(path);
		ret = PTR_ERR(trans);
		goto out;
	}

	dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
	di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
				   dir_id, "default", 7, 1);
	if (IS_ERR_OR_NULL(di)) {
		btrfs_free_path(path);
		btrfs_end_transaction(trans, root);
		printk(KERN_ERR "Umm, you don't have the default dir item, "
		       "this isn't going to work\n");
		ret = -ENOENT;
		goto out;
	}

	btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
	btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
	btrfs_mark_buffer_dirty(path->nodes[0]);
	btrfs_free_path(path);

	btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
	btrfs_end_transaction(trans, root);
out:
	mnt_drop_write_file(file);
	return ret;
}


static tmsize_t _tiffWriteProc ( thandle_t fd , void * buf , tmsize_t size ) {
 fd_as_handle_union_t fdh ;
 const size_t bytes_total = ( size_t ) size ;
 size_t bytes_written ;
 tmsize_t count = - 1 ;
 if ( ( tmsize_t ) bytes_total != size ) {
 errno = EINVAL ;
 return ( tmsize_t ) - 1 ;
 }
 fdh . h = fd ;
 for ( bytes_written = 0 ;
 bytes_written < bytes_total ;
 bytes_written += count ) {
 const char * buf_offset = ( char * ) buf + bytes_written ;
 size_t io_size = bytes_total - bytes_written ;
 if ( io_size > TIFF_IO_MAX ) io_size = TIFF_IO_MAX ;
 count = write ( fdh . fd , buf_offset , ( TIFFIOSize_t ) io_size ) ;
 if ( count <= 0 ) break ;
 }
 if ( count < 0 ) return ( tmsize_t ) - 1 ;
 return ( tmsize_t ) bytes_written ;
 }


void BinaryUploadService::ResetAuthorizationData() {
  can_upload_data_ = base::nullopt;

  IsAuthorized(base::DoNothing());
}


static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
	{
	int cmp;
	unsigned int shift;
	const unsigned char *seq = s->s3->read_sequence;

	cmp = satsub64be(seq,bitmap->max_seq_num);
	if (cmp > 0)
		{
		shift = cmp;
		if (shift < sizeof(bitmap->map)*8)
			bitmap->map <<= shift, bitmap->map |= 1UL;
		else
			bitmap->map = 1UL;
		memcpy(bitmap->max_seq_num,seq,8);
		}
	else	{
		shift = -cmp;
		if (shift < sizeof(bitmap->map)*8)
			bitmap->map |= 1UL<<shift;
		}
	}


TEST_F(SPDY3DownstreamSessionTest, SpdyTimeoutWin) {
  clientCodec_->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
                                                500);
  clientCodec_->generateSettings(requests_);
  auto streamID = sendRequest();

  InSequence handlerSequence;
  auto handler = addSimpleStrictHandler();
  handler->expectHeaders();
  handler->expectEOM([&] {
      handler->sendReplyWithBody(200, 1000);
    });
  handler->expectEgressPaused();
  handler->expectError([&] (const HTTPException& ex) {
      ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
      ASSERT_EQ(
        folly::to<std::string>("ingress timeout, streamID=", streamID),
        std::string(ex.what()));
      handler->terminate();
    });
  handler->expectDetachTransaction();

  flushRequestsAndLoop();

  cleanup();
}


QPDF::EncryptionData::getOE() const
{
    return this->OE;
}


bool MemFile::rewind() {
  assertx(m_len != -1);
  m_cursor = 0;
  setWritePosition(0);
  setReadPosition(0);
  setPosition(0);
  return true;
}


static int rose_del_node(struct rose_route_struct *rose_route,
	struct net_device *dev)
{
	struct rose_node  *rose_node;
	struct rose_neigh *rose_neigh;
	int i, err = 0;

	spin_lock_bh(&rose_node_list_lock);
	spin_lock_bh(&rose_neigh_list_lock);

	rose_node = rose_node_list;
	while (rose_node != NULL) {
		if ((rose_node->mask == rose_route->mask) &&
		    (rosecmpm(&rose_route->address, &rose_node->address,
			      rose_route->mask) == 0))
			break;
		rose_node = rose_node->next;
	}

	if (rose_node == NULL || rose_node->loopback) {
		err = -EINVAL;
		goto out;
	}

	rose_neigh = rose_neigh_list;
	while (rose_neigh != NULL) {
		if (ax25cmp(&rose_route->neighbour,
			    &rose_neigh->callsign) == 0 &&
		    rose_neigh->dev == dev)
			break;
		rose_neigh = rose_neigh->next;
	}

	if (rose_neigh == NULL) {
		err = -EINVAL;
		goto out;
	}

	for (i = 0; i < rose_node->count; i++) {
		if (rose_node->neighbour[i] == rose_neigh) {
			rose_neigh->count--;

			if (rose_neigh->count == 0 && rose_neigh->use == 0)
				rose_remove_neigh(rose_neigh);

			rose_node->count--;

			if (rose_node->count == 0) {
				rose_remove_node(rose_node);
			} else {
				switch (i) {
				case 0:
					rose_node->neighbour[0] =
						rose_node->neighbour[1];
				case 1:
					rose_node->neighbour[1] =
						rose_node->neighbour[2];
				case 2:
					break;
				}
			}
			goto out;
		}
	}
	err = -EINVAL;

out:
	spin_unlock_bh(&rose_neigh_list_lock);
	spin_unlock_bh(&rose_node_list_lock);

	return err;
}


static bool parsePrefetchNode(QSvgNode *parent,
                              const QXmlStreamAttributes &attributes,
                              QSvgHandler *)
{
    Q_UNUSED(parent); Q_UNUSED(attributes);
    return true;
}


static void flatview_simplify(FlatView *view)
{
    unsigned i, j;

    i = 0;
    while (i < view->nr) {
        j = i + 1;
        while (j < view->nr
               && can_merge(&view->ranges[j-1], &view->ranges[j])) {
            int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
            ++j;
        }
        ++i;
        memmove(&view->ranges[i], &view->ranges[j],
                (view->nr - j) * sizeof(view->ranges[j]));
        view->nr -= j - i;
    }
}


static Indirect *ext4_find_shared(struct inode *inode, int depth,
				  ext4_lblk_t offsets[4], Indirect chain[4],
				  __le32 *top)
{
	Indirect *partial, *p;
	int k, err;

	*top = 0;
	/* Make k index the deepest non-null offset + 1 */
	for (k = depth; k > 1 && !offsets[k-1]; k--)
		;
	partial = ext4_get_branch(inode, k, offsets, chain, &err);
	/* Writer: pointers */
	if (!partial)
		partial = chain + k-1;
	/*
	 * If the branch acquired continuation since we've looked at it -
	 * fine, it should all survive and (new) top doesn't belong to us.
	 */
	if (!partial->key && *partial->p)
		/* Writer: end */
		goto no_top;
	for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
		;
	/*
	 * OK, we've found the last block that must survive. The rest of our
	 * branch should be detached before unlocking. However, if that rest
	 * of branch is all ours and does not grow immediately from the inode
	 * it's easier to cheat and just decrement partial->p.
	 */
	if (p == chain + k - 1 && p > chain) {
		p->p--;
	} else {
		*top = *p->p;
		/* Nope, don't do this in ext4.  Must leave the tree intact */
#if 0
		*p->p = 0;
#endif
	}
	/* Writer: end */

	while (partial > p) {
		brelse(partial->bh);
		partial--;
	}
no_top:
	return partial;
}


void DBDMA_register_channel(void *dbdma, int nchan, qemu_irq irq,

                            DBDMA_rw rw, DBDMA_flush flush,

                            void *opaque)

{

    DBDMAState *s = dbdma;

    DBDMA_channel *ch = &s->channels[nchan];

    DBDMA_DPRINTF("DBDMA_register_channel 0x%x\n", nchan);

    ch->irq = irq;

    ch->channel = nchan;

    ch->rw = rw;

    ch->flush = flush;

    ch->io.opaque = opaque;

    ch->io.channel = ch;

}


static int magicmouse_probe(struct hid_device *hdev,
	const struct hid_device_id *id)
{
	__u8 feature[] = { 0xd7, 0x01 };
	struct magicmouse_sc *msc;
	struct hid_report *report;
	int ret;

	msc = devm_kzalloc(&hdev->dev, sizeof(*msc), GFP_KERNEL);
	if (msc == NULL) {
		hid_err(hdev, "can't alloc magicmouse descriptor\n");
		return -ENOMEM;
	}

	msc->scroll_accel = SCROLL_ACCEL_DEFAULT;

	msc->quirks = id->driver_data;
	hid_set_drvdata(hdev, msc);

	ret = hid_parse(hdev);
	if (ret) {
		hid_err(hdev, "magicmouse hid parse failed\n");
		return ret;
	}

	ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
	if (ret) {
		hid_err(hdev, "magicmouse hw start failed\n");
		return ret;
	}

	if (!msc->input) {
		hid_err(hdev, "magicmouse input not registered\n");
		ret = -ENOMEM;
		goto err_stop_hw;
	}

	if (id->product == USB_DEVICE_ID_APPLE_MAGICMOUSE)
		report = hid_register_report(hdev, HID_INPUT_REPORT,
			MOUSE_REPORT_ID);
	else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */
		report = hid_register_report(hdev, HID_INPUT_REPORT,
			TRACKPAD_REPORT_ID);
		report = hid_register_report(hdev, HID_INPUT_REPORT,
			DOUBLE_REPORT_ID);
	}

	if (!report) {
		hid_err(hdev, "unable to register touch report\n");
		ret = -ENOMEM;
		goto err_stop_hw;
	}
	report->size = 6;

	/*
	 * Some devices repond with 'invalid report id' when feature
	 * report switching it into multitouch mode is sent to it.
	 *
	 * This results in -EIO from the _raw low-level transport callback,
	 * but there seems to be no other way of switching the mode.
	 * Thus the super-ugly hacky success check below.
	 */
	ret = hid_hw_raw_request(hdev, feature[0], feature, sizeof(feature),
				HID_FEATURE_REPORT, HID_REQ_SET_REPORT);
	if (ret != -EIO && ret != sizeof(feature)) {
		hid_err(hdev, "unable to request touch data (%d)\n", ret);
		goto err_stop_hw;
	}

	return 0;
err_stop_hw:
	hid_hw_stop(hdev);
	return ret;
}


IN_PROC_BROWSER_TEST_F ( DownloadExtensionTest , DownloadExtensionTest_OnDeterminingFilename_Overwrite ) {
 GoOnTheRecord ( ) ;
 LoadExtension ( "downloads_split" ) ;
 AddFilenameDeterminer ( ) ;
 ASSERT_TRUE ( StartEmbeddedTestServer ( ) ) ;
 std : : string download_url = embedded_test_server ( ) -> GetURL ( "/slow?0" ) . spec ( ) ;
 std : : unique_ptr < base : : Value > result ( RunFunctionAndReturnResult ( new DownloadsDownloadFunction ( ) , base : : StringPrintf ( "[{
\"url\": \"%s\"}
]" , download_url . c_str ( ) ) ) ) ;
 ASSERT_TRUE ( result . get ( ) ) ;
 int result_id = - 1 ;
 ASSERT_TRUE ( result -> GetAsInteger ( & result_id ) ) ;
 DownloadItem * item = GetCurrentManager ( ) -> GetDownload ( result_id ) ;
 ASSERT_TRUE ( item ) ;
 ScopedCancellingItem canceller ( item ) ;
 ASSERT_EQ ( download_url , item -> GetOriginalUrl ( ) . spec ( ) ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnCreated : : kEventName , base : : StringPrintf ( "[{
\"danger\": \"safe\"," " \"incognito\": false," " \"id\": %d," " \"mime\": \"text/plain\"," " \"paused\": false," " \"url\": \"%s\"}
]" , result_id , download_url . c_str ( ) ) ) ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnDeterminingFilename : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"filename\":\"slow.txt\"}
]" , result_id ) ) ) ;
 ASSERT_TRUE ( item -> GetTargetFilePath ( ) . empty ( ) ) ;
 ASSERT_EQ ( DownloadItem : : IN_PROGRESS , item -> GetState ( ) ) ;
 std : : string error ;
 ASSERT_TRUE ( ExtensionDownloadsEventRouter : : DetermineFilename ( browser ( ) -> profile ( ) , false , GetExtensionId ( ) , result_id , base : : FilePath ( ) , downloads : : FILENAME_CONFLICT_ACTION_UNIQUIFY , & error ) ) ;
 EXPECT_EQ ( "" , error ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnChanged : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"filename\": {
" " \"previous\": \"\"," " \"current\": \"%s\"}
}
]" , result_id , GetFilename ( "slow.txt" ) . c_str ( ) ) ) ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnChanged : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"state\": {
" " \"previous\": \"in_progress\"," " \"current\": \"complete\"}
}
]" , result_id ) ) ) ;
 result . reset ( RunFunctionAndReturnResult ( new DownloadsDownloadFunction ( ) , base : : StringPrintf ( "[{
\"url\": \"%s\"}
]" , download_url . c_str ( ) ) ) ) ;
 ASSERT_TRUE ( result . get ( ) ) ;
 result_id = - 1 ;
 ASSERT_TRUE ( result -> GetAsInteger ( & result_id ) ) ;
 item = GetCurrentManager ( ) -> GetDownload ( result_id ) ;
 ASSERT_TRUE ( item ) ;
 ScopedCancellingItem canceller2 ( item ) ;
 ASSERT_EQ ( download_url , item -> GetOriginalUrl ( ) . spec ( ) ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnCreated : : kEventName , base : : StringPrintf ( "[{
\"danger\": \"safe\"," " \"incognito\": false," " \"id\": %d," " \"mime\": \"text/plain\"," " \"paused\": false," " \"url\": \"%s\"}
]" , result_id , download_url . c_str ( ) ) ) ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnDeterminingFilename : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"filename\":\"slow.txt\"}
]" , result_id ) ) ) ;
 ASSERT_TRUE ( item -> GetTargetFilePath ( ) . empty ( ) ) ;
 ASSERT_EQ ( DownloadItem : : IN_PROGRESS , item -> GetState ( ) ) ;
 error = "" ;
 ASSERT_TRUE ( ExtensionDownloadsEventRouter : : DetermineFilename ( browser ( ) -> profile ( ) , false , GetExtensionId ( ) , result_id , base : : FilePath ( ) , downloads : : FILENAME_CONFLICT_ACTION_OVERWRITE , & error ) ) ;
 EXPECT_EQ ( "" , error ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnChanged : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"filename\": {
" " \"previous\": \"\"," " \"current\": \"%s\"}
}
]" , result_id , GetFilename ( "slow.txt" ) . c_str ( ) ) ) ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnChanged : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"state\": {
" " \"previous\": \"in_progress\"," " \"current\": \"complete\"}
}
]" , result_id ) ) ) ;
 }


static BOOL rdp_print_large_pointer_capability_set(wStream* s, UINT16 length)
{
	UINT16 largePointerSupportFlags;
	WLog_INFO(TAG, "LargePointerCapabilitySet (length %" PRIu16 "):", length);

	if (length < 6)
		return FALSE;

	Stream_Read_UINT16(s, largePointerSupportFlags); /* largePointerSupportFlags (2 bytes) */
	WLog_INFO(TAG, "\tlargePointerSupportFlags: 0x%04" PRIX16 "", largePointerSupportFlags);
	return TRUE;
}


void RenderFrameImpl::PrepareRenderViewForNavigation(
    const GURL& url,
    const RequestNavigationParams& request_params) {
  DCHECK(render_view_->webview());

  if (is_main_frame_) {
    for (auto& observer : render_view_->observers_)
      observer.Navigate(url);
  }

  render_view_->history_list_offset_ =
      request_params.current_history_list_offset;
  render_view_->history_list_length_ =
      request_params.current_history_list_length;
}


bool OxideQQuickWebView::loading() const {
  Q_D(const OxideQQuickWebView);

  if (!d->proxy_) {
    return false;
  }

  return d->proxy_->loading();
}


int ieee80211_radiotap_iterator_init ( struct ieee80211_radiotap_iterator * iterator , struct ieee80211_radiotap_header * radiotap_header , int max_length , const struct ieee80211_radiotap_vendor_namespaces * vns ) {
 if ( max_length < ( int ) sizeof ( struct ieee80211_radiotap_header ) ) return - EINVAL ;
 if ( radiotap_header -> it_version ) return - EINVAL ;
 if ( max_length < get_unaligned_le16 ( & radiotap_header -> it_len ) ) return - EINVAL ;
 iterator -> _rtheader = radiotap_header ;
 iterator -> _max_length = get_unaligned_le16 ( & radiotap_header -> it_len ) ;
 iterator -> _arg_index = 0 ;
 iterator -> _bitmap_shifter = get_unaligned_le32 ( & radiotap_header -> it_present ) ;
 iterator -> _arg = ( guint8 * ) radiotap_header + sizeof ( * radiotap_header ) ;
 iterator -> _reset_on_ext = 0 ;
 iterator -> _next_bitmap = & radiotap_header -> it_present ;
 iterator -> _next_bitmap ++ ;
 iterator -> _vns = vns ;
 iterator -> current_namespace = & radiotap_ns ;
 iterator -> is_radiotap_ns = 1 ;
 # ifdef RADIOTAP_SUPPORT_OVERRIDES iterator -> n_overrides = 0 ;
 iterator -> overrides = NULL ;
 # endif if ( iterator -> _bitmap_shifter & ( 1U << IEEE80211_RADIOTAP_EXT ) ) {
 if ( ! ITERATOR_VALID ( iterator , sizeof ( guint32 ) ) ) return - EINVAL ;
 while ( get_unaligned_le32 ( iterator -> _arg ) & ( 1U << IEEE80211_RADIOTAP_EXT ) ) {
 iterator -> _arg += sizeof ( guint32 ) ;
 if ( ! ITERATOR_VALID ( iterator , sizeof ( guint32 ) ) ) return - EINVAL ;
 }
 iterator -> _arg += sizeof ( guint32 ) ;
 }
 iterator -> this_arg = iterator -> _arg ;
 return 0 ;
 }


static void get_client_info(struct snd_seq_client *cptr,
			    struct snd_seq_client_info *info)
{
	info->client = cptr->number;

	/* fill the info fields */
	info->type = cptr->type;
	strcpy(info->name, cptr->name);
	info->filter = cptr->filter;
	info->event_lost = cptr->event_lost;
	memcpy(info->event_filter, cptr->event_filter, 32);
	info->num_ports = cptr->num_ports;
	memset(info->reserved, 0, sizeof(info->reserved));
}


    UserCloudPolicyManagerFactoryChromeOS::GetManagerForProfile(
        Profile* profile) {
  ManagerMap::const_iterator it = managers_.find(profile->GetOriginalProfile());
  return it != managers_.end() ? it->second : NULL;
}


static gboolean match_hostname(const char *cert_hostname, const char *hostname)
{
	const char *hostname_left;

	if (!strcasecmp(cert_hostname, hostname)) { /* exact match */
		return TRUE;
	} else if (cert_hostname[0] == '*' && cert_hostname[1] == '.' && cert_hostname[2] != 0) { /* wildcard match */
		/* The initial '*' matches exactly one hostname component */
		hostname_left = strchr(hostname, '.');
		if (hostname_left != NULL && ! strcasecmp(hostname_left + 1, cert_hostname + 2)) {
			return TRUE;
		}
	}
	return FALSE;
}


bool DocumentLoader::ShouldPersistUserGestureValue(
    const SecurityOrigin* previous_security_origin,
    const SecurityOrigin* new_security_origin) {
  if (!CheckOriginIsHttpOrHttps(previous_security_origin) ||
      !CheckOriginIsHttpOrHttps(new_security_origin))
    return false;

  if (previous_security_origin->Host() == new_security_origin->Host())
    return true;

  String previous_domain = NetworkUtils::GetDomainAndRegistry(
      previous_security_origin->Host(),
      NetworkUtils::kIncludePrivateRegistries);
  String new_domain = NetworkUtils::GetDomainAndRegistry(
      new_security_origin->Host(), NetworkUtils::kIncludePrivateRegistries);

  return !previous_domain.IsEmpty() && previous_domain == new_domain;
}


void end_server(MYSQL *mysql)
{
  int save_errno= errno;
  DBUG_ENTER("end_server");
  if (mysql->net.vio != 0)
  {
    DBUG_PRINT("info",("Net: %s", vio_description(mysql->net.vio)));
#ifdef MYSQL_SERVER
    slave_io_thread_detach_vio();
#endif
    vio_delete(mysql->net.vio);
    mysql->net.vio= 0;          /* Marker */
    mysql_prune_stmt_list(mysql);
  }
  net_end(&mysql->net);
  free_old_query(mysql);
  errno= save_errno;
  MYSQL_TRACE(DISCONNECTED, mysql, ());
  DBUG_VOID_RETURN;
}


static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
{
	if (kvm_arch_vcpu_runnable(vcpu)) {
		kvm_make_request(KVM_REQ_UNHALT, vcpu);
		return -EINTR;
	}
	if (kvm_cpu_has_pending_timer(vcpu))
		return -EINTR;
	if (signal_pending(current))
		return -EINTR;

	return 0;
}


  ~AudioSourceProviderClientLockScope() {
    if (client_)
      client_->unlock();
  }


void TabStrip::PaintClosingTabs(gfx::Canvas* canvas, int index) {
  if (tabs_closing_map_.find(index) == tabs_closing_map_.end())
    return;

  const std::vector<Tab*>& tabs = tabs_closing_map_[index];
  for (std::vector<Tab*>::const_reverse_iterator i(tabs.rbegin());
       i != tabs.rend(); ++i) {
    (*i)->Paint(canvas);
  }
}


void PrintPnode(ParseNode *pnode) {
    PrintPnodeWIndent(pnode,0);
}


static uint16_t nvme_del_sq(NvmeCtrl *n, NvmeCmd *cmd)

{

    NvmeDeleteQ *c = (NvmeDeleteQ *)cmd;

    NvmeRequest *req, *next;

    NvmeSQueue *sq;

    NvmeCQueue *cq;

    uint16_t qid = le16_to_cpu(c->qid);

    if (!qid || nvme_check_sqid(n, qid)) {

        return NVME_INVALID_QID | NVME_DNR;

    }

    sq = n->sq[qid];

    while (!QTAILQ_EMPTY(&sq->out_req_list)) {

        req = QTAILQ_FIRST(&sq->out_req_list);

        assert(req->aiocb);

        blk_aio_cancel(req->aiocb);

    }

    if (!nvme_check_cqid(n, sq->cqid)) {

        cq = n->cq[sq->cqid];

        QTAILQ_REMOVE(&cq->sq_list, sq, entry);

        nvme_post_cqes(cq);

        QTAILQ_FOREACH_SAFE(req, &cq->req_list, entry, next) {

            if (req->sq == sq) {

                QTAILQ_REMOVE(&cq->req_list, req, entry);

                QTAILQ_INSERT_TAIL(&sq->req_list, req, entry);

            }

        }

    }

    nvme_free_sq(sq, n);

    return NVME_SUCCESS;

}


void sws_freeContext(SwsContext *c)

{

    int i;

    if (!c) return;

    if (c->lumPixBuf) {

        for (i=0; i<c->vLumBufSize; i++)

            av_freep(&c->lumPixBuf[i]);

        av_freep(&c->lumPixBuf);

    }

    if (c->chrPixBuf) {

        for (i=0; i<c->vChrBufSize; i++)

            av_freep(&c->chrPixBuf[i]);

        av_freep(&c->chrPixBuf);

    }

    if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

        for (i=0; i<c->vLumBufSize; i++)

            av_freep(&c->alpPixBuf[i]);

        av_freep(&c->alpPixBuf);

    }

    av_freep(&c->vLumFilter);

    av_freep(&c->vChrFilter);

    av_freep(&c->hLumFilter);

    av_freep(&c->hChrFilter);

#if ARCH_PPC && HAVE_ALTIVEC

    av_freep(&c->vYCoeffsBank);

    av_freep(&c->vCCoeffsBank);

#endif

    av_freep(&c->vLumFilterPos);

    av_freep(&c->vChrFilterPos);

    av_freep(&c->hLumFilterPos);

    av_freep(&c->hChrFilterPos);

#if ARCH_X86 && CONFIG_GPL

#ifdef MAP_ANONYMOUS

    if (c->lumMmx2FilterCode) munmap(c->lumMmx2FilterCode, c->lumMmx2FilterCodeSize);

    if (c->chrMmx2FilterCode) munmap(c->chrMmx2FilterCode, c->chrMmx2FilterCodeSize);

#elif HAVE_VIRTUALALLOC

    if (c->lumMmx2FilterCode) VirtualFree(c->lumMmx2FilterCode, 0, MEM_RELEASE);

    if (c->chrMmx2FilterCode) VirtualFree(c->chrMmx2FilterCode, 0, MEM_RELEASE);

#else

    av_free(c->lumMmx2FilterCode);

    av_free(c->chrMmx2FilterCode);

#endif

    c->lumMmx2FilterCode=NULL;

    c->chrMmx2FilterCode=NULL;

#endif /* ARCH_X86 && CONFIG_GPL */

    av_freep(&c->yuvTable);

    av_free(c);

}


static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
 size_t bytes)
{
 struct a2dp_stream_in *in = (struct a2dp_stream_in *)stream;
 int read;

    DEBUG("read %zu bytes, state: %d", bytes, in->common.state);

 if (in->common.state == AUDIO_A2DP_STATE_SUSPENDED)
 {
        DEBUG("stream suspended");
 return -1;
 }

 /* only allow autostarting if we are in stopped or standby */
 if ((in->common.state == AUDIO_A2DP_STATE_STOPPED) ||
 (in->common.state == AUDIO_A2DP_STATE_STANDBY))
 {
        pthread_mutex_lock(&in->common.lock);

 if (start_audio_datapath(&in->common) < 0)
 {
 /* emulate time this write represents to avoid very fast write
               failures during transition periods or remote suspend */

 int us_delay = calc_audiotime(in->common.cfg, bytes);

             DEBUG("emulate a2dp read delay (%d us)", us_delay);

            usleep(us_delay);
             pthread_mutex_unlock(&in->common.lock);
             return -1;
         }

        pthread_mutex_unlock(&in->common.lock);
 }
 else if (in->common.state != AUDIO_A2DP_STATE_STARTED)
 {
        ERROR("stream not in stopped or standby");
 return -1;
 }

    read = skt_read(in->common.audio_fd, buffer, bytes);

 if (read == -1)
 {
        skt_disconnect(in->common.audio_fd);
        in->common.audio_fd = AUDIO_SKT_DISCONNECTED;
        in->common.state = AUDIO_A2DP_STATE_STOPPED;
 } else if (read == 0) {
        DEBUG("read time out - return zeros");
        memset(buffer, 0, bytes);
        read = bytes;
 }

    DEBUG("read %d bytes out of %zu bytes", read, bytes);
 return read;
}


void f2fs_wait_on_encrypted_page_writeback(struct f2fs_sb_info *sbi,
							block_t blkaddr)
{
	struct page *cpage;

	if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
		return;

	cpage = find_lock_page(META_MAPPING(sbi), blkaddr);
	if (cpage) {
		f2fs_wait_on_page_writeback(cpage, DATA, true);
		f2fs_put_page(cpage, 1);
	}
}


static int hevc_handle_packet(AVFormatContext *ctx, PayloadContext *rtp_hevc_ctx,

                              AVStream *st, AVPacket *pkt, uint32_t *timestamp,

                              const uint8_t *buf, int len, uint16_t seq,

                              int flags)

{

    const uint8_t *rtp_pl = buf;

    int tid, lid, nal_type;

    int first_fragment, last_fragment, fu_type;

    uint8_t new_nal_header[2];

    int res = 0;

    /* sanity check for size of input packet: 1 byte payload at least */

    if (len < RTP_HEVC_PAYLOAD_HEADER_SIZE + 1) {

        av_log(ctx, AV_LOG_ERROR, "Too short RTP/HEVC packet, got %d bytes\n", len);

        return AVERROR_INVALIDDATA;

    }

    /*

      decode the HEVC payload header according to section 4 of draft version 6:

         0                   1

         0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5

        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

        |F|   Type    |  LayerId  | TID |

        +-------------+-----------------+

           Forbidden zero (F): 1 bit

           NAL unit type (Type): 6 bits

           NUH layer ID (LayerId): 6 bits

           NUH temporal ID plus 1 (TID): 3 bits

    */

    nal_type =  (buf[0] >> 1) & 0x3f;

    lid  = ((buf[0] << 5) & 0x20) | ((buf[1] >> 3) & 0x1f);

    tid  =   buf[1] & 0x07;

    /* sanity check for correct layer ID */

    if (lid) {

        /* future scalable or 3D video coding extensions */

        avpriv_report_missing_feature(ctx, "Multi-layer HEVC coding\n");

        return AVERROR_PATCHWELCOME;

    }

    /* sanity check for correct temporal ID */

    if (!tid) {

        av_log(ctx, AV_LOG_ERROR, "Illegal temporal ID in RTP/HEVC packet\n");

        return AVERROR_INVALIDDATA;

    }

    /* sanity check for correct NAL unit type */

    if (nal_type > 50) {

        av_log(ctx, AV_LOG_ERROR, "Unsupported (HEVC) NAL type (%d)\n", nal_type);

        return AVERROR_INVALIDDATA;

    }

    switch (nal_type) {

    /* aggregated packets (AP) */

    case 48:

        /* pass the HEVC payload header */

        buf += RTP_HEVC_PAYLOAD_HEADER_SIZE;

        len -= RTP_HEVC_PAYLOAD_HEADER_SIZE;

        /* pass the HEVC DONL field */

        if (rtp_hevc_ctx->using_donl_field) {

            buf += RTP_HEVC_DONL_FIELD_SIZE;

            len -= RTP_HEVC_DONL_FIELD_SIZE;

        }

        /* fall-through */

    /* video parameter set (VPS) */

    case 32:

    /* sequence parameter set (SPS) */

    case 33:

    /* picture parameter set (PPS) */

    case 34:

    /*  supplemental enhancement information (SEI) */

    case 39:

    /* single NAL unit packet */

    default:

        /* sanity check for size of input packet: 1 byte payload at least */

        if (len < 1) {

            av_log(ctx, AV_LOG_ERROR,

                   "Too short RTP/HEVC packet, got %d bytes of NAL unit type %d\n",

                   len, nal_type);

            return AVERROR_INVALIDDATA;

        }

        /* create A/V packet */

        if ((res = av_new_packet(pkt, sizeof(start_sequence) + len)) < 0)

            return res;

        /* A/V packet: copy start sequence */

        memcpy(pkt->data, start_sequence, sizeof(start_sequence));

        /* A/V packet: copy NAL unit data */

        memcpy(pkt->data + sizeof(start_sequence), buf, len);

        break;

    /* fragmentation unit (FU) */

    case 49:

        /* pass the HEVC payload header */

        buf += RTP_HEVC_PAYLOAD_HEADER_SIZE;

        len -= RTP_HEVC_PAYLOAD_HEADER_SIZE;

        if (len < 1)

            return AVERROR_INVALIDDATA;

        /*

             decode the FU header

              0 1 2 3 4 5 6 7

             +-+-+-+-+-+-+-+-+

             |S|E|  FuType   |

             +---------------+

                Start fragment (S): 1 bit

                End fragment (E): 1 bit

                FuType: 6 bits

        */

        first_fragment = buf[0] & 0x80;

        last_fragment  = buf[0] & 0x40;

        fu_type        = buf[0] & 0x3f;

        /* pass the HEVC FU header */

        buf += RTP_HEVC_FU_HEADER_SIZE;

        len -= RTP_HEVC_FU_HEADER_SIZE;

        /* pass the HEVC DONL field */

        if (rtp_hevc_ctx->using_donl_field) {

            buf += RTP_HEVC_DONL_FIELD_SIZE;

            len -= RTP_HEVC_DONL_FIELD_SIZE;

        }

        av_dlog(ctx, " FU type %d with %d bytes\n", fu_type, len);

        if (len > 0) {

            new_nal_header[0] = (rtp_pl[0] & 0x81) | (fu_type << 1);

            new_nal_header[1] = rtp_pl[1];

            /* start fragment vs. subsequent fragments */

            if (first_fragment) {

                if (!last_fragment) {

                    /* create A/V packet which is big enough */

                    if ((res = av_new_packet(pkt, sizeof(start_sequence) + sizeof(new_nal_header) + len)) < 0)

                        return res;

                    /* A/V packet: copy start sequence */

                    memcpy(pkt->data, start_sequence, sizeof(start_sequence));

                    /* A/V packet: copy new NAL header */

                    memcpy(pkt->data + sizeof(start_sequence), new_nal_header, sizeof(new_nal_header));

                    /* A/V packet: copy NAL unit data */

                    memcpy(pkt->data + sizeof(start_sequence) + sizeof(new_nal_header), buf, len);

                } else {

                    av_log(ctx, AV_LOG_ERROR, "Illegal combination of S and E bit in RTP/HEVC packet\n");

                    res = AVERROR_INVALIDDATA;

                }

            } else {

                /* create A/V packet */

                if ((res = av_new_packet(pkt, len)) < 0)

                    return res;

                /* A/V packet: copy NAL unit data */

                memcpy(pkt->data, buf, len);

            }

        } else {

            /* sanity check for size of input packet: 1 byte payload at least */

            av_log(ctx, AV_LOG_ERROR,

                   "Too short RTP/HEVC packet, got %d bytes of NAL unit type %d\n",

                   len, nal_type);

            res = AVERROR_INVALIDDATA;

        }

        break;

    /* PACI packet */

    case 50:

        /* Temporal scalability control information (TSCI) */

        avpriv_report_missing_feature(ctx, "PACI packets for RTP/HEVC\n");

        res = AVERROR_PATCHWELCOME;

        break;

    }

    pkt->stream_index = st->index;

    return res;

}


  void Compute(OpKernelContext* ctx) override {
    const Tensor& arr_t = ctx->input(0);
    const Tensor& size_tensor = ctx->input(1);
    OP_REQUIRES(ctx, size_tensor.dims() == 0,
                errors::InvalidArgument("Shape must be rank 0 but is rank ",
                                        size_tensor.dims()));
    int32_t size = size_tensor.scalar<int32_t>()();
    OP_REQUIRES(
        ctx, size >= 0,
        errors::InvalidArgument("size (", size, ") must be non-negative"));

    const Tensor& weights_t = ctx->input(2);
    const auto arr = arr_t.flat<int32_t>();
    const auto weights = weights_t.flat<T>();
    Tensor* output_t;
    OP_REQUIRES_OK(ctx,
                   ctx->allocate_output(0, TensorShape({size}), &output_t));
    auto output = output_t->flat<T>();
    OP_REQUIRES_OK(ctx,
                   functor::BincountFunctor<Device, int32_t, T, false>::Compute(
                       ctx, arr, weights, output, size));
  }


int enumcfg(char *group, char *param, int psize, char *value, int vsize, int index) {
   int i;

   for (i = 0; i < n_lb_config; i++)
      if (strieq(group, lb_config[i].section_name)) {

         if (index < lb_config[i].n_params) {
            strlcpy(param, lb_config[i].config_param[index].param, psize);
            strlcpy(value, lb_config[i].config_param[index].value, vsize);
            return 1;
         }

         return 0;

      }

   return 0;
}


static int nl80211_get_mesh_config(struct sk_buff *skb,
				   struct genl_info *info)
{
	struct cfg80211_registered_device *rdev = info->user_ptr[0];
	struct net_device *dev = info->user_ptr[1];
	struct wireless_dev *wdev = dev->ieee80211_ptr;
	struct mesh_config cur_params;
	int err = 0;
	void *hdr;
	struct nlattr *pinfoattr;
	struct sk_buff *msg;

	if (wdev->iftype != NL80211_IFTYPE_MESH_POINT)
		return -EOPNOTSUPP;

	if (!rdev->ops->get_mesh_config)
		return -EOPNOTSUPP;

	wdev_lock(wdev);
	/* If not connected, get default parameters */
	if (!wdev->mesh_id_len)
		memcpy(&cur_params, &default_mesh_config, sizeof(cur_params));
	else
		err = rdev->ops->get_mesh_config(&rdev->wiphy, dev,
						 &cur_params);
	wdev_unlock(wdev);

	if (err)
		return err;

	/* Draw up a netlink message to send back */
	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
	if (!msg)
		return -ENOMEM;
	hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
			     NL80211_CMD_GET_MESH_CONFIG);
	if (!hdr)
		goto out;
	pinfoattr = nla_nest_start(msg, NL80211_ATTR_MESH_CONFIG);
	if (!pinfoattr)
		goto nla_put_failure;
	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, dev->ifindex);
	NLA_PUT_U16(msg, NL80211_MESHCONF_RETRY_TIMEOUT,
			cur_params.dot11MeshRetryTimeout);
	NLA_PUT_U16(msg, NL80211_MESHCONF_CONFIRM_TIMEOUT,
			cur_params.dot11MeshConfirmTimeout);
	NLA_PUT_U16(msg, NL80211_MESHCONF_HOLDING_TIMEOUT,
			cur_params.dot11MeshHoldingTimeout);
	NLA_PUT_U16(msg, NL80211_MESHCONF_MAX_PEER_LINKS,
			cur_params.dot11MeshMaxPeerLinks);
	NLA_PUT_U8(msg, NL80211_MESHCONF_MAX_RETRIES,
			cur_params.dot11MeshMaxRetries);
	NLA_PUT_U8(msg, NL80211_MESHCONF_TTL,
			cur_params.dot11MeshTTL);
	NLA_PUT_U8(msg, NL80211_MESHCONF_ELEMENT_TTL,
			cur_params.element_ttl);
	NLA_PUT_U8(msg, NL80211_MESHCONF_AUTO_OPEN_PLINKS,
			cur_params.auto_open_plinks);
	NLA_PUT_U8(msg, NL80211_MESHCONF_HWMP_MAX_PREQ_RETRIES,
			cur_params.dot11MeshHWMPmaxPREQretries);
	NLA_PUT_U32(msg, NL80211_MESHCONF_PATH_REFRESH_TIME,
			cur_params.path_refresh_time);
	NLA_PUT_U16(msg, NL80211_MESHCONF_MIN_DISCOVERY_TIMEOUT,
			cur_params.min_discovery_timeout);
	NLA_PUT_U32(msg, NL80211_MESHCONF_HWMP_ACTIVE_PATH_TIMEOUT,
			cur_params.dot11MeshHWMPactivePathTimeout);
	NLA_PUT_U16(msg, NL80211_MESHCONF_HWMP_PREQ_MIN_INTERVAL,
			cur_params.dot11MeshHWMPpreqMinInterval);
	NLA_PUT_U16(msg, NL80211_MESHCONF_HWMP_NET_DIAM_TRVS_TIME,
			cur_params.dot11MeshHWMPnetDiameterTraversalTime);
	NLA_PUT_U8(msg, NL80211_MESHCONF_HWMP_ROOTMODE,
			cur_params.dot11MeshHWMPRootMode);
	nla_nest_end(msg, pinfoattr);
	genlmsg_end(msg, hdr);
	return genlmsg_reply(msg, info);

 nla_put_failure:
	genlmsg_cancel(msg, hdr);
 out:
	nlmsg_free(msg);
	return -ENOBUFS;
}


static void task_numa_group(struct task_struct *p, int cpupid, int flags,
			int *priv)
{
	struct numa_group *grp, *my_grp;
	struct task_struct *tsk;
	bool join = false;
	int cpu = cpupid_to_cpu(cpupid);
	int i;

	if (unlikely(!p->numa_group)) {
		unsigned int size = sizeof(struct numa_group) +
				    4*nr_node_ids*sizeof(unsigned long);

		grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
		if (!grp)
			return;

		atomic_set(&grp->refcount, 1);
		grp->active_nodes = 1;
		grp->max_faults_cpu = 0;
		spin_lock_init(&grp->lock);
		grp->gid = p->pid;
		/* Second half of the array tracks nids where faults happen */
		grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
						nr_node_ids;

		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
			grp->faults[i] = p->numa_faults[i];

		grp->total_faults = p->total_numa_faults;

		grp->nr_tasks++;
		rcu_assign_pointer(p->numa_group, grp);
	}

	rcu_read_lock();
	tsk = READ_ONCE(cpu_rq(cpu)->curr);

	if (!cpupid_match_pid(tsk, cpupid))
		goto no_join;

	grp = rcu_dereference(tsk->numa_group);
	if (!grp)
		goto no_join;

	my_grp = p->numa_group;
	if (grp == my_grp)
		goto no_join;

	/*
	 * Only join the other group if its bigger; if we're the bigger group,
	 * the other task will join us.
	 */
	if (my_grp->nr_tasks > grp->nr_tasks)
		goto no_join;

	/*
	 * Tie-break on the grp address.
	 */
	if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
		goto no_join;

	/* Always join threads in the same process. */
	if (tsk->mm == current->mm)
		join = true;

	/* Simple filter to avoid false positives due to PID collisions */
	if (flags & TNF_SHARED)
		join = true;

	/* Update priv based on whether false sharing was detected */
	*priv = !join;

	if (join && !get_numa_group(grp))
		goto no_join;

	rcu_read_unlock();

	if (!join)
		return;

	BUG_ON(irqs_disabled());
	double_lock_irq(&my_grp->lock, &grp->lock);

	for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
		my_grp->faults[i] -= p->numa_faults[i];
		grp->faults[i] += p->numa_faults[i];
	}
	my_grp->total_faults -= p->total_numa_faults;
	grp->total_faults += p->total_numa_faults;

	my_grp->nr_tasks--;
	grp->nr_tasks++;

	spin_unlock(&my_grp->lock);
	spin_unlock_irq(&grp->lock);

	rcu_assign_pointer(p->numa_group, grp);

	put_numa_group(my_grp);
	return;

no_join:
	rcu_read_unlock();
	return;
}


void WebContents::DownloadURL(const GURL& url) {
  auto* browser_context = web_contents()->GetBrowserContext();
  auto* download_manager =
      content::BrowserContext::GetDownloadManager(browser_context);
  std::unique_ptr<download::DownloadUrlParameters> download_params(
      content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
          web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
  download_manager->DownloadUrl(std::move(download_params));
}


static void vfio_msi_disable(struct vfio_pci_device *vdev, bool msix)
{
	struct pci_dev *pdev = vdev->pdev;
	int i;

	for (i = 0; i < vdev->num_ctx; i++) {
		vfio_virqfd_disable(&vdev->ctx[i].unmask);
		vfio_virqfd_disable(&vdev->ctx[i].mask);
	}

	vfio_msi_set_block(vdev, 0, vdev->num_ctx, NULL, msix);

	pci_free_irq_vectors(pdev);

	/*
	 * Both disable paths above use pci_intx_for_msi() to clear DisINTx
	 * via their shutdown paths.  Restore for NoINTx devices.
	 */
	if (vdev->nointx)
		pci_intx(pdev, 0);

	vdev->irq_type = VFIO_PCI_NUM_IRQS;
	vdev->num_ctx = 0;
	kfree(vdev->ctx);
}


static bool gen_wsr_ccompare(DisasContext *dc, uint32_t sr, TCGv_i32 v)

{

    uint32_t id = sr - CCOMPARE;

    bool ret = false;

    if (id < dc->config->nccompare) {

        uint32_t int_bit = 1 << dc->config->timerint[id];

        TCGv_i32 tmp = tcg_const_i32(id);

        tcg_gen_mov_i32(cpu_SR[sr], v);

        tcg_gen_andi_i32(cpu_SR[INTSET], cpu_SR[INTSET], ~int_bit);

        if (dc->tb->cflags & CF_USE_ICOUNT) {

            gen_io_start();

        }

        gen_helper_update_ccompare(cpu_env, tmp);

        if (dc->tb->cflags & CF_USE_ICOUNT) {

            gen_io_end();

            gen_jumpi_check_loop_end(dc, 0);

            ret = true;

        }

        tcg_temp_free(tmp);

    }

    return ret;

}


void FrameFetchContext::DidLoadResource(Resource* resource) {
  if (!document_)
    return;
  FirstMeaningfulPaintDetector::From(*document_).CheckNetworkStable();
  if (LocalFrame* local_frame = document_->GetFrame()) {
    if (IdlenessDetector* idleness_detector =
            local_frame->GetIdlenessDetector()) {
      idleness_detector->OnDidLoadResource();
    }
  }

  if (resource->IsLoadEventBlockingResourceType())
    document_->CheckCompleted();
}


static int php_rinit_session(zend_bool auto_start TSRMLS_DC) /* {{{ */
{
	php_rinit_session_globals(TSRMLS_C);

	if (PS(mod) == NULL) {
		char *value;

		value = zend_ini_string("session.save_handler", sizeof("session.save_handler"), 0);
		if (value) {
			PS(mod) = _php_find_ps_module(value TSRMLS_CC);
		}
	}

	if (PS(serializer) == NULL) {
		char *value;

		value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler"), 0);
		if (value) {
			PS(serializer) = _php_find_ps_serializer(value TSRMLS_CC);
		}
	}

	if (PS(mod) == NULL || PS(serializer) == NULL) {
		/* current status is unusable */
		PS(session_status) = php_session_disabled;
		return SUCCESS;
	}

	if (auto_start) {
		php_session_start(TSRMLS_C);
	}

	return SUCCESS;
} /* }}} */


void EvalHybridPerChannel(TfLiteContext* context, TfLiteNode* node,
                          TfLiteConvParams* params, OpData* data,
                          const TfLiteTensor* input, const TfLiteTensor* filter,
                          const TfLiteTensor* bias, TfLiteTensor* im2col,
                          TfLiteTensor* output) {
  float output_activation_min, output_activation_max;
  CalculateActivationRange(params->activation, &output_activation_min,
                           &output_activation_max);

  const int input_size = NumElements(input) / SizeOfDimension(input, 0);
  const int batch_size = SizeOfDimension(input, 0);
  int8_t* quantized_input_ptr_batch = GetTensorData<int8_t>(
      GetTemporary(context, node, data->input_quantized_index));
  float* scaling_factors_ptr = GetTensorData<float>(
      GetTemporary(context, node, data->scaling_factors_index));
  int32_t* input_offset_ptr = GetTensorData<int32_t>(
      GetTemporary(context, node, data->input_offset_index));

  for (int b = 0; b < batch_size; ++b) {
    const int offset = b * input_size;
    tensor_utils::AsymmetricQuantizeFloats(
        GetTensorData<float>(input) + offset, input_size,
        quantized_input_ptr_batch + offset, &scaling_factors_ptr[b],
        &input_offset_ptr[b]);
  }

  int8_t* im2col_ptr = nullptr;
  int8_t* filter_ptr = nullptr;
  if (im2col != nullptr) {
    im2col_ptr = im2col->data.int8;
  }
  filter_ptr = filter->data.int8;
  const auto* affine_quantization =
      reinterpret_cast<TfLiteAffineQuantization*>(filter->quantization.params);
  ConvParams op_params;
  op_params.padding_type = PaddingType::kSame;
  op_params.padding_values.width = data->padding.width;
  op_params.padding_values.height = data->padding.height;
  op_params.stride_width = params->stride_width;
  op_params.stride_height = params->stride_height;
  op_params.dilation_width_factor = 1;
  op_params.dilation_height_factor = 1;
  op_params.float_activation_min = output_activation_min;
  op_params.float_activation_max = output_activation_max;
  switch (kernel_type) {
    case kReference:
      reference_ops::HybridConvPerChannel(
          op_params, scaling_factors_ptr, GetTensorShape(input),
          quantized_input_ptr_batch, GetTensorShape(filter), filter_ptr,
          GetTensorShape(bias), GetTensorData<float>(bias),
          GetTensorShape(output), GetTensorData<float>(output),
          GetTensorShape(im2col), im2col_ptr, affine_quantization->scale->data,
          input_offset_ptr);
      break;
    case kGenericOptimized:
    case kMultithreadOptimized:
    case kCblasOptimized: {
      TfLiteTensor* row_sums =
          GetTemporary(context, node, data->row_sums_index);
      TfLiteTensor* scratch =
          GetTemporary(context, node, data->accum_scratch_index);
      optimized_ops::HybridConvPerChannel(
          op_params, scaling_factors_ptr, GetTensorShape(input),
          quantized_input_ptr_batch, GetTensorShape(filter), filter_ptr,
          GetTensorShape(bias), GetTensorData<float>(bias),
          GetTensorShape(output), GetTensorData<float>(output),
          GetTensorShape(im2col), im2col_ptr, affine_quantization->scale->data,
          input_offset_ptr, GetTensorShape(scratch),
          GetTensorData<int32>(scratch), GetTensorData<int32_t>(row_sums),
          &data->compute_hybrid_row_sums,
          CpuBackendContext::GetFromContext(context));
      data->compute_hybrid_row_sums = false;
      break;
    }
  }
}


  adisplay_init( ADisplay     display,
                 grPixelMode  mode )
  {
    grSurface*  surface;
    grBitmap    bit;

    if ( mode != gr_pixel_mode_gray  &&
         mode != gr_pixel_mode_rgb24 )
      return -1;

    grInitDevices();

    bit.mode  = mode;
    bit.width = DIM_X;
    bit.rows  = DIM_Y;
    bit.grays = 256;

    surface = grNewSurface( 0, &bit );

    if ( !surface )
      return -1;

    display->surface = surface;
    display->bitmap  = &surface->bitmap;
    display->gamma   = 1.0;

    grSetGlyphGamma( display->gamma );

    memset( &display->fore_color, 0, sizeof( grColor ) );
    memset( &display->back_color, 0xff, sizeof( grColor ) );

    return 0;
  }


ELFOBJ* Elf_(r_bin_elf_new_buf)(RBuffer *buf, bool verbose) {
	ELFOBJ *bin = R_NEW0 (ELFOBJ);
	bin->kv = sdb_new0 ();
	bin->b = r_buf_new ();
	bin->size = (ut32)buf->length;
	bin->verbose = verbose;
	if (!r_buf_set_bytes (bin->b, buf->buf, buf->length)) {
		return Elf_(r_bin_elf_free) (bin);
	}
	if (!elf_init (bin)) {
		return Elf_(r_bin_elf_free) (bin);
	}
	return bin;
}


void AutofillDialogViews::ContentsChanged(views::Textfield* sender,
                                          const base::string16& new_contents) {
  InputEditedOrActivated(TypeForTextfield(sender),
                         sender->GetBoundsInScreen(),
                         true);

  const ExpandingTextfield* expanding = static_cast<ExpandingTextfield*>(
      sender->GetAncestorWithClassName(ExpandingTextfield::kViewClassName));
  if (expanding && expanding->needs_layout())
    ContentsPreferredSizeChanged();
}


static int tg3_phy_auxctl_write(struct tg3 *tp, int reg, u32 set)
{
	if (reg == MII_TG3_AUXCTL_SHDWSEL_MISC)
		set |= MII_TG3_AUXCTL_MISC_WREN;

	return tg3_writephy(tp, MII_TG3_AUX_CTRL, set | reg);
}


int arg_parse_enum(const struct arg *arg) {
 const struct arg_enum_list *listptr;
 long int                    rawval;
 char *endptr;

 /* First see if the value can be parsed as a raw value */
  rawval = strtol(arg->val, &endptr, 10);
 if (arg->val[0] != '\0' && endptr[0] == '\0') {
 /* Got a raw value, make sure it's valid */
 for (listptr = arg->def->enums; listptr->name; listptr++)
 if (listptr->val == rawval)
 return rawval;
 }

 /* Next see if it can be parsed as a string */
 for (listptr = arg->def->enums; listptr->name; listptr++)
 if (!strcmp(arg->val, listptr->name))
 return listptr->val;

  die("Option %s: Invalid value '%s'\n", arg->name, arg->val);
 return 0;
}


void setJSTestObjWithScriptArgumentsAndCallStackAttribute(ExecState* exec, JSObject* thisObject, JSValue value)
{
    JSTestObj* castedThis = jsCast<JSTestObj*>(thisObject);
    TestObj* impl = static_cast<TestObj*>(castedThis->impl());
    RefPtr<ScriptCallStack> callStack(createScriptCallStackForInspector(exec));
    impl->setWithScriptArgumentsAndCallStackAttribute(callStack, toTestObj(value));
}


add_pack_start_dirs(void)
{
    do_in_path(p_pp, (char_u *)"pack/*/start/*", DIP_ALL + DIP_DIR,
					       add_pack_plugin, &APP_ADD_DIR);
}


static void StreamTcpSessionPoolCleanup(void *s)
{
    if (s != NULL) {
        StreamTcpSessionCleanup(s);
        /** \todo not very clean, as the memory is not freed here */
        StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
    }
}


static void lsr_read_coord_list(GF_LASeRCodec *lsr, GF_Node *elt, u32 tag, const char *name)
{
	GF_FieldInfo info;
	u32 i, count;
	GF_LSR_READ_INT(lsr, count, 1, name);
	if (!count) return;
	count = lsr_read_vluimsbf5(lsr, "nb_coords");
	if (!count) return;

	lsr->last_error = gf_node_get_attribute_by_tag(elt, tag, GF_TRUE, 0, &info);

	for (i=0; i<count; i++) {
		u32 res;
		SVG_Coordinate *f;
		GF_SAFEALLOC(f, SVG_Coordinate );
		if (!f) {
			lsr->last_error = GF_OUT_OF_MEM;
			return;
		}
		GF_LSR_READ_INT(lsr, res, lsr->coord_bits, name);
		f->value = lsr_translate_coords(lsr, res, lsr->coord_bits);
		gf_list_add(*(SVG_Coordinates*)info.far_ptr, f);
		if (lsr->last_error) return;
	}
}


void UserCloudPolicyManagerChromeOS::OnClientError(
    CloudPolicyClient* cloud_policy_client) {
  DCHECK_EQ(client(), cloud_policy_client);
  if (wait_for_policy_fetch_) {
    UMA_HISTOGRAM_SPARSE_SLOWLY(kUMAInitialFetchClientError,
                                cloud_policy_client->status());
  }
  CancelWaitForPolicyFetch();
}


_logLuvNop(LogLuvState* sp, uint8* op, tmsize_t n)
{
	(void) sp; (void) op; (void) n;
}


  virtual ~SwichToMetroUIHandler() {
    default_browser_worker_->ObserverDestroyed();
  }


void vp9_lpf_horizontal_8_dual_sse2 ( uint8_t * s , int p , const uint8_t * _blimit0 , const uint8_t * _limit0 , const uint8_t * _thresh0 , const uint8_t * _blimit1 , const uint8_t * _limit1 , const uint8_t * _thresh1 ) {
 DECLARE_ALIGNED_ARRAY ( 16 , unsigned char , flat_op2 , 16 ) ;
 DECLARE_ALIGNED_ARRAY ( 16 , unsigned char , flat_op1 , 16 ) ;
 DECLARE_ALIGNED_ARRAY ( 16 , unsigned char , flat_op0 , 16 ) ;
 DECLARE_ALIGNED_ARRAY ( 16 , unsigned char , flat_oq2 , 16 ) ;
 DECLARE_ALIGNED_ARRAY ( 16 , unsigned char , flat_oq1 , 16 ) ;
 DECLARE_ALIGNED_ARRAY ( 16 , unsigned char , flat_oq0 , 16 ) ;
 const __m128i zero = _mm_set1_epi16 ( 0 ) ;
 const __m128i blimit = _mm_unpacklo_epi64 ( _mm_load_si128 ( ( const __m128i * ) _blimit0 ) , _mm_load_si128 ( ( const __m128i * ) _blimit1 ) ) ;
 const __m128i limit = _mm_unpacklo_epi64 ( _mm_load_si128 ( ( const __m128i * ) _limit0 ) , _mm_load_si128 ( ( const __m128i * ) _limit1 ) ) ;
 const __m128i thresh = _mm_unpacklo_epi64 ( _mm_load_si128 ( ( const __m128i * ) _thresh0 ) , _mm_load_si128 ( ( const __m128i * ) _thresh1 ) ) ;
 __m128i mask , hev , flat ;
 __m128i p3 , p2 , p1 , p0 , q0 , q1 , q2 , q3 ;
 p3 = _mm_loadu_si128 ( ( __m128i * ) ( s - 4 * p ) ) ;
 p2 = _mm_loadu_si128 ( ( __m128i * ) ( s - 3 * p ) ) ;
 p1 = _mm_loadu_si128 ( ( __m128i * ) ( s - 2 * p ) ) ;
 p0 = _mm_loadu_si128 ( ( __m128i * ) ( s - 1 * p ) ) ;
 q0 = _mm_loadu_si128 ( ( __m128i * ) ( s - 0 * p ) ) ;
 q1 = _mm_loadu_si128 ( ( __m128i * ) ( s + 1 * p ) ) ;
 q2 = _mm_loadu_si128 ( ( __m128i * ) ( s + 2 * p ) ) ;
 q3 = _mm_loadu_si128 ( ( __m128i * ) ( s + 3 * p ) ) ;
 {
 const __m128i abs_p1p0 = _mm_or_si128 ( _mm_subs_epu8 ( p1 , p0 ) , _mm_subs_epu8 ( p0 , p1 ) ) ;
 const __m128i abs_q1q0 = _mm_or_si128 ( _mm_subs_epu8 ( q1 , q0 ) , _mm_subs_epu8 ( q0 , q1 ) ) ;
 const __m128i one = _mm_set1_epi8 ( 1 ) ;
 const __m128i fe = _mm_set1_epi8 ( 0xfe ) ;
 const __m128i ff = _mm_cmpeq_epi8 ( abs_p1p0 , abs_p1p0 ) ;
 __m128i abs_p0q0 = _mm_or_si128 ( _mm_subs_epu8 ( p0 , q0 ) , _mm_subs_epu8 ( q0 , p0 ) ) ;
 __m128i abs_p1q1 = _mm_or_si128 ( _mm_subs_epu8 ( p1 , q1 ) , _mm_subs_epu8 ( q1 , p1 ) ) ;
 __m128i work ;
 flat = _mm_max_epu8 ( abs_p1p0 , abs_q1q0 ) ;
 hev = _mm_subs_epu8 ( flat , thresh ) ;
 hev = _mm_xor_si128 ( _mm_cmpeq_epi8 ( hev , zero ) , ff ) ;
 abs_p0q0 = _mm_adds_epu8 ( abs_p0q0 , abs_p0q0 ) ;
 abs_p1q1 = _mm_srli_epi16 ( _mm_and_si128 ( abs_p1q1 , fe ) , 1 ) ;
 mask = _mm_subs_epu8 ( _mm_adds_epu8 ( abs_p0q0 , abs_p1q1 ) , blimit ) ;
 mask = _mm_xor_si128 ( _mm_cmpeq_epi8 ( mask , zero ) , ff ) ;
 mask = _mm_max_epu8 ( flat , mask ) ;
 work = _mm_max_epu8 ( _mm_or_si128 ( _mm_subs_epu8 ( p2 , p1 ) , _mm_subs_epu8 ( p1 , p2 ) ) , _mm_or_si128 ( _mm_subs_epu8 ( p3 , p2 ) , _mm_subs_epu8 ( p2 , p3 ) ) ) ;
 mask = _mm_max_epu8 ( work , mask ) ;
 work = _mm_max_epu8 ( _mm_or_si128 ( _mm_subs_epu8 ( q2 , q1 ) , _mm_subs_epu8 ( q1 , q2 ) ) , _mm_or_si128 ( _mm_subs_epu8 ( q3 , q2 ) , _mm_subs_epu8 ( q2 , q3 ) ) ) ;
 mask = _mm_max_epu8 ( work , mask ) ;
 mask = _mm_subs_epu8 ( mask , limit ) ;
 mask = _mm_cmpeq_epi8 ( mask , zero ) ;
 work = _mm_max_epu8 ( _mm_or_si128 ( _mm_subs_epu8 ( p2 , p0 ) , _mm_subs_epu8 ( p0 , p2 ) ) , _mm_or_si128 ( _mm_subs_epu8 ( q2 , q0 ) , _mm_subs_epu8 ( q0 , q2 ) ) ) ;
 flat = _mm_max_epu8 ( work , flat ) ;
 work = _mm_max_epu8 ( _mm_or_si128 ( _mm_subs_epu8 ( p3 , p0 ) , _mm_subs_epu8 ( p0 , p3 ) ) , _mm_or_si128 ( _mm_subs_epu8 ( q3 , q0 ) , _mm_subs_epu8 ( q0 , q3 ) ) ) ;
 flat = _mm_max_epu8 ( work , flat ) ;
 flat = _mm_subs_epu8 ( flat , one ) ;
 flat = _mm_cmpeq_epi8 ( flat , zero ) ;
 flat = _mm_and_si128 ( flat , mask ) ;
 }
 {
 const __m128i four = _mm_set1_epi16 ( 4 ) ;
 unsigned char * src = s ;
 int i = 0 ;
 do {
 __m128i workp_a , workp_b , workp_shft ;
 p3 = _mm_unpacklo_epi8 ( _mm_loadl_epi64 ( ( __m128i * ) ( src - 4 * p ) ) , zero ) ;
 p2 = _mm_unpacklo_epi8 ( _mm_loadl_epi64 ( ( __m128i * ) ( src - 3 * p ) ) , zero ) ;
 p1 = _mm_unpacklo_epi8 ( _mm_loadl_epi64 ( ( __m128i * ) ( src - 2 * p ) ) , zero ) ;
 p0 = _mm_unpacklo_epi8 ( _mm_loadl_epi64 ( ( __m128i * ) ( src - 1 * p ) ) , zero ) ;
 q0 = _mm_unpacklo_epi8 ( _mm_loadl_epi64 ( ( __m128i * ) ( src - 0 * p ) ) , zero ) ;
 q1 = _mm_unpacklo_epi8 ( _mm_loadl_epi64 ( ( __m128i * ) ( src + 1 * p ) ) , zero ) ;
 q2 = _mm_unpacklo_epi8 ( _mm_loadl_epi64 ( ( __m128i * ) ( src + 2 * p ) ) , zero ) ;
 q3 = _mm_unpacklo_epi8 ( _mm_loadl_epi64 ( ( __m128i * ) ( src + 3 * p ) ) , zero ) ;
 workp_a = _mm_add_epi16 ( _mm_add_epi16 ( p3 , p3 ) , _mm_add_epi16 ( p2 , p1 ) ) ;
 workp_a = _mm_add_epi16 ( _mm_add_epi16 ( workp_a , four ) , p0 ) ;
 workp_b = _mm_add_epi16 ( _mm_add_epi16 ( q0 , p2 ) , p3 ) ;
 workp_shft = _mm_srli_epi16 ( _mm_add_epi16 ( workp_a , workp_b ) , 3 ) ;
 _mm_storel_epi64 ( ( __m128i * ) & flat_op2 [ i * 8 ] , _mm_packus_epi16 ( workp_shft , workp_shft ) ) ;
 workp_b = _mm_add_epi16 ( _mm_add_epi16 ( q0 , q1 ) , p1 ) ;
 workp_shft = _mm_srli_epi16 ( _mm_add_epi16 ( workp_a , workp_b ) , 3 ) ;
 _mm_storel_epi64 ( ( __m128i * ) & flat_op1 [ i * 8 ] , _mm_packus_epi16 ( workp_shft , workp_shft ) ) ;
 workp_a = _mm_add_epi16 ( _mm_sub_epi16 ( workp_a , p3 ) , q2 ) ;
 workp_b = _mm_add_epi16 ( _mm_sub_epi16 ( workp_b , p1 ) , p0 ) ;
 workp_shft = _mm_srli_epi16 ( _mm_add_epi16 ( workp_a , workp_b ) , 3 ) ;
 _mm_storel_epi64 ( ( __m128i * ) & flat_op0 [ i * 8 ] , _mm_packus_epi16 ( workp_shft , workp_shft ) ) ;
 workp_a = _mm_add_epi16 ( _mm_sub_epi16 ( workp_a , p3 ) , q3 ) ;
 workp_b = _mm_add_epi16 ( _mm_sub_epi16 ( workp_b , p0 ) , q0 ) ;
 workp_shft = _mm_srli_epi16 ( _mm_add_epi16 ( workp_a , workp_b ) , 3 ) ;
 _mm_storel_epi64 ( ( __m128i * ) & flat_oq0 [ i * 8 ] , _mm_packus_epi16 ( workp_shft , workp_shft ) ) ;
 workp_a = _mm_add_epi16 ( _mm_sub_epi16 ( workp_a , p2 ) , q3 ) ;
 workp_b = _mm_add_epi16 ( _mm_sub_epi16 ( workp_b , q0 ) , q1 ) ;
 workp_shft = _mm_srli_epi16 ( _mm_add_epi16 ( workp_a , workp_b ) , 3 ) ;
 _mm_storel_epi64 ( ( __m128i * ) & flat_oq1 [ i * 8 ] , _mm_packus_epi16 ( workp_shft , workp_shft ) ) ;
 workp_a = _mm_add_epi16 ( _mm_sub_epi16 ( workp_a , p1 ) , q3 ) ;
 workp_b = _mm_add_epi16 ( _mm_sub_epi16 ( workp_b , q1 ) , q2 ) ;
 workp_shft = _mm_srli_epi16 ( _mm_add_epi16 ( workp_a , workp_b ) , 3 ) ;
 _mm_storel_epi64 ( ( __m128i * ) & flat_oq2 [ i * 8 ] , _mm_packus_epi16 ( workp_shft , workp_shft ) ) ;
 src += 8 ;
 }
 while ( ++ i < 2 ) ;
 }
 {
 const __m128i t4 = _mm_set1_epi8 ( 4 ) ;
 const __m128i t3 = _mm_set1_epi8 ( 3 ) ;
 const __m128i t80 = _mm_set1_epi8 ( 0x80 ) ;
 const __m128i te0 = _mm_set1_epi8 ( 0xe0 ) ;
 const __m128i t1f = _mm_set1_epi8 ( 0x1f ) ;
 const __m128i t1 = _mm_set1_epi8 ( 0x1 ) ;
 const __m128i t7f = _mm_set1_epi8 ( 0x7f ) ;
 const __m128i ps1 = _mm_xor_si128 ( _mm_loadu_si128 ( ( __m128i * ) ( s - 2 * p ) ) , t80 ) ;
 const __m128i ps0 = _mm_xor_si128 ( _mm_loadu_si128 ( ( __m128i * ) ( s - 1 * p ) ) , t80 ) ;
 const __m128i qs0 = _mm_xor_si128 ( _mm_loadu_si128 ( ( __m128i * ) ( s + 0 * p ) ) , t80 ) ;
 const __m128i qs1 = _mm_xor_si128 ( _mm_loadu_si128 ( ( __m128i * ) ( s + 1 * p ) ) , t80 ) ;
 __m128i filt ;
 __m128i work_a ;
 __m128i filter1 , filter2 ;
 filt = _mm_and_si128 ( _mm_subs_epi8 ( ps1 , qs1 ) , hev ) ;
 work_a = _mm_subs_epi8 ( qs0 , ps0 ) ;
 filt = _mm_adds_epi8 ( filt , work_a ) ;
 filt = _mm_adds_epi8 ( filt , work_a ) ;
 filt = _mm_adds_epi8 ( filt , work_a ) ;
 filt = _mm_and_si128 ( filt , mask ) ;
 filter1 = _mm_adds_epi8 ( filt , t4 ) ;
 filter2 = _mm_adds_epi8 ( filt , t3 ) ;
 work_a = _mm_cmpgt_epi8 ( zero , filter1 ) ;
 filter1 = _mm_srli_epi16 ( filter1 , 3 ) ;
 work_a = _mm_and_si128 ( work_a , te0 ) ;
 filter1 = _mm_and_si128 ( filter1 , t1f ) ;
 filter1 = _mm_or_si128 ( filter1 , work_a ) ;
 work_a = _mm_cmpgt_epi8 ( zero , filter2 ) ;
 filter2 = _mm_srli_epi16 ( filter2 , 3 ) ;
 work_a = _mm_and_si128 ( work_a , te0 ) ;
 filter2 = _mm_and_si128 ( filter2 , t1f ) ;
 filter2 = _mm_or_si128 ( filter2 , work_a ) ;
 filt = _mm_adds_epi8 ( filter1 , t1 ) ;
 work_a = _mm_cmpgt_epi8 ( zero , filt ) ;
 filt = _mm_srli_epi16 ( filt , 1 ) ;
 work_a = _mm_and_si128 ( work_a , t80 ) ;
 filt = _mm_and_si128 ( filt , t7f ) ;
 filt = _mm_or_si128 ( filt , work_a ) ;
 filt = _mm_andnot_si128 ( hev , filt ) ;
 work_a = _mm_xor_si128 ( _mm_subs_epi8 ( qs0 , filter1 ) , t80 ) ;
 q0 = _mm_load_si128 ( ( __m128i * ) flat_oq0 ) ;
 work_a = _mm_andnot_si128 ( flat , work_a ) ;
 q0 = _mm_and_si128 ( flat , q0 ) ;
 q0 = _mm_or_si128 ( work_a , q0 ) ;
 work_a = _mm_xor_si128 ( _mm_subs_epi8 ( qs1 , filt ) , t80 ) ;
 q1 = _mm_load_si128 ( ( __m128i * ) flat_oq1 ) ;
 work_a = _mm_andnot_si128 ( flat , work_a ) ;
 q1 = _mm_and_si128 ( flat , q1 ) ;
 q1 = _mm_or_si128 ( work_a , q1 ) ;
 work_a = _mm_loadu_si128 ( ( __m128i * ) ( s + 2 * p ) ) ;
 q2 = _mm_load_si128 ( ( __m128i * ) flat_oq2 ) ;
 work_a = _mm_andnot_si128 ( flat , work_a ) ;
 q2 = _mm_and_si128 ( flat , q2 ) ;
 q2 = _mm_or_si128 ( work_a , q2 ) ;
 work_a = _mm_xor_si128 ( _mm_adds_epi8 ( ps0 , filter2 ) , t80 ) ;
 p0 = _mm_load_si128 ( ( __m128i * ) flat_op0 ) ;
 work_a = _mm_andnot_si128 ( flat , work_a ) ;
 p0 = _mm_and_si128 ( flat , p0 ) ;
 p0 = _mm_or_si128 ( work_a , p0 ) ;
 work_a = _mm_xor_si128 ( _mm_adds_epi8 ( ps1 , filt ) , t80 ) ;
 p1 = _mm_load_si128 ( ( __m128i * ) flat_op1 ) ;
 work_a = _mm_andnot_si128 ( flat , work_a ) ;
 p1 = _mm_and_si128 ( flat , p1 ) ;
 p1 = _mm_or_si128 ( work_a , p1 ) ;
 work_a = _mm_loadu_si128 ( ( __m128i * ) ( s - 3 * p ) ) ;
 p2 = _mm_load_si128 ( ( __m128i * ) flat_op2 ) ;
 work_a = _mm_andnot_si128 ( flat , work_a ) ;
 p2 = _mm_and_si128 ( flat , p2 ) ;
 p2 = _mm_or_si128 ( work_a , p2 ) ;
 _mm_storeu_si128 ( ( __m128i * ) ( s - 3 * p ) , p2 ) ;
 _mm_storeu_si128 ( ( __m128i * ) ( s - 2 * p ) , p1 ) ;
 _mm_storeu_si128 ( ( __m128i * ) ( s - 1 * p ) , p0 ) ;
 _mm_storeu_si128 ( ( __m128i * ) ( s + 0 * p ) , q0 ) ;
 _mm_storeu_si128 ( ( __m128i * ) ( s + 1 * p ) , q1 ) ;
 _mm_storeu_si128 ( ( __m128i * ) ( s + 2 * p ) , q2 ) ;
 }
 }


static void baum_chr_open(Chardev *chr,

                          ChardevBackend *backend,

                          bool *be_opened,

                          Error **errp)

{

    BaumChardev *baum = BAUM_CHARDEV(chr);

    brlapi_handle_t *handle;

    handle = g_malloc0(brlapi_getHandleSize());

    baum->brlapi = handle;

    baum->brlapi_fd = brlapi__openConnection(handle, NULL, NULL);

    if (baum->brlapi_fd == -1) {

        error_setg(errp, "brlapi__openConnection: %s",

                   brlapi_strerror(brlapi_error_location()));

        g_free(handle);

        return;

    }

    baum->deferred_init = 0;

    baum->cellCount_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, baum_cellCount_timer_cb, baum);

    qemu_set_fd_handler(baum->brlapi_fd, baum_chr_read, NULL, baum);

}


static TypedValue* serialize_vars_helper(ActRec* ar) {
  WddxPacket* wddxPacket = newres<WddxPacket>(empty_string_variant_ref,
                                              true, true);
  int start_index = 0;
  for (int i = start_index; i < ar->numArgs(); i++) {
    auto const tv = getArg(ar, i);
    find_var_recursive(tv, wddxPacket);
  }
  Variant packet = wddxPacket->packet_end();
  return arReturn(ar, std::move(packet));
}


static void print_service_rules_icmp(HttpResponse res, Service_T s) {
        for (Icmp_T i = s->icmplist; i; i = i->next) {
                switch (i->family) {
                        case Socket_Ip4:
                                StringBuffer_append(res->outputbuffer, "
Ping4	");
                                break;
                        case Socket_Ip6:
                                StringBuffer_append(res->outputbuffer, "
Ping6	");
                                break;
                        default:
                                StringBuffer_append(res->outputbuffer, "
Ping	");
                                break;
                }
                Util_printRule(res->outputbuffer, i->action, "If failed [count %d size %d with timeout %s%s%s]", i->count, i->size, Str_milliToTime(i->timeout, (char[23]){}), i->outgoing.ip ? " via address " : "", i->outgoing.ip ? i->outgoing.ip : "");
                StringBuffer_append(res->outputbuffer, "
");
        }
}


void FS_AddGameDirectory( const char *path, const char *dir ) {
	searchpath_t    *sp;
	int i;
	searchpath_t    *search;
	pack_t          *pak;
	char            *pakfile;
	int numfiles;
	char            **pakfiles;
	char            *sorted[MAX_PAKFILES];

	for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
		if ( sp->dir && !Q_stricmp( sp->dir->path, path ) && !Q_stricmp( sp->dir->gamedir, dir ) ) {
			return;         // we've already got this one
		}
	}

	Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );

	search = Z_Malloc( sizeof( searchpath_t ) );
	search->dir = Z_Malloc( sizeof( *search->dir ) );

	Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) );
	Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) );
	search->next = fs_searchpaths;
	fs_searchpaths = search;

	pakfile = FS_BuildOSPath( path, dir, "" );
	pakfile[ strlen( pakfile ) - 1 ] = 0; // strip the trailing slash

	pakfiles = Sys_ListFiles( pakfile, ".pk3", NULL, &numfiles, qfalse );

	if ( numfiles > MAX_PAKFILES ) {
		numfiles = MAX_PAKFILES;
	}
	for ( i = 0 ; i < numfiles ; i++ ) {
		sorted[i] = pakfiles[i];

		if ( !Q_strncmp( sorted[i],"sp_",3 ) ) { //	sort sp first
			memcpy( sorted[i],"zz",2 );
		}

	}

	qsort( sorted, numfiles, sizeof(char *), paksort );

	for ( i = 0 ; i < numfiles ; i++ ) {

		if ( Q_strncmp( sorted[i],"mp_",3 ) ) { // (SA) SP mod -- exclude mp_*

			if ( !Q_strncmp( sorted[i],"zz_",3 ) ) {
				memcpy( sorted[i],"sp",2 );
			}

			pakfile = FS_BuildOSPath( path, dir, sorted[i] );
			if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 ) {
				continue;
			}
			strcpy( pak->pakGamename, dir );

			search = Z_Malloc( sizeof( searchpath_t ) );
			search->pack = pak;
			search->next = fs_searchpaths;
			fs_searchpaths = search;
		}
	}

	Sys_FreeFileList( pakfiles );
}


static void msvideo1_decode_8bit ( Msvideo1Context * s ) {
 int block_ptr , pixel_ptr ;
 int total_blocks ;
 int pixel_x , pixel_y ;
 int block_x , block_y ;
 int blocks_wide , blocks_high ;
 int block_inc ;
 int row_dec ;
 int stream_ptr ;
 unsigned char byte_a , byte_b ;
 unsigned short flags ;
 int skip_blocks ;
 unsigned char colors [ 8 ] ;
 unsigned char * pixels = s -> frame . data [ 0 ] ;
 int stride = s -> frame . linesize [ 0 ] ;
 stream_ptr = 0 ;
 skip_blocks = 0 ;
 blocks_wide = s -> avctx -> width / 4 ;
 blocks_high = s -> avctx -> height / 4 ;
 total_blocks = blocks_wide * blocks_high ;
 block_inc = 4 ;
 row_dec = stride + 4 ;
 for ( block_y = blocks_high ;
 block_y > 0 ;
 block_y -- ) {
 block_ptr = ( ( block_y * 4 ) - 1 ) * stride ;
 for ( block_x = blocks_wide ;
 block_x > 0 ;
 block_x -- ) {
 if ( skip_blocks ) {
 block_ptr += block_inc ;
 skip_blocks -- ;
 total_blocks -- ;
 continue ;
 }
 pixel_ptr = block_ptr ;
 CHECK_STREAM_PTR ( 2 ) ;
 byte_a = s -> buf [ stream_ptr ++ ] ;
 byte_b = s -> buf [ stream_ptr ++ ] ;
 if ( ( byte_a == 0 ) && ( byte_b == 0 ) && ( total_blocks == 0 ) ) return ;
 else if ( ( byte_b & 0xFC ) == 0x84 ) {
 skip_blocks = ( ( byte_b - 0x84 ) << 8 ) + byte_a - 1 ;
 }
 else if ( byte_b < 0x80 ) {
 flags = ( byte_b << 8 ) | byte_a ;
 CHECK_STREAM_PTR ( 2 ) ;
 colors [ 0 ] = s -> buf [ stream_ptr ++ ] ;
 colors [ 1 ] = s -> buf [ stream_ptr ++ ] ;
 for ( pixel_y = 0 ;
 pixel_y < 4 ;
 pixel_y ++ ) {
 for ( pixel_x = 0 ;
 pixel_x < 4 ;
 pixel_x ++ , flags >>= 1 ) pixels [ pixel_ptr ++ ] = colors [ ( flags & 0x1 ) ^ 1 ] ;
 pixel_ptr -= row_dec ;
 }
 }
 else if ( byte_b >= 0x90 ) {
 flags = ( byte_b << 8 ) | byte_a ;
 CHECK_STREAM_PTR ( 8 ) ;
 memcpy ( colors , & s -> buf [ stream_ptr ] , 8 ) ;
 stream_ptr += 8 ;
 for ( pixel_y = 0 ;
 pixel_y < 4 ;
 pixel_y ++ ) {
 for ( pixel_x = 0 ;
 pixel_x < 4 ;
 pixel_x ++ , flags >>= 1 ) pixels [ pixel_ptr ++ ] = colors [ ( ( pixel_y & 0x2 ) << 1 ) + ( pixel_x & 0x2 ) + ( ( flags & 0x1 ) ^ 1 ) ] ;
 pixel_ptr -= row_dec ;
 }
 }
 else {
 colors [ 0 ] = byte_a ;
 for ( pixel_y = 0 ;
 pixel_y < 4 ;
 pixel_y ++ ) {
 for ( pixel_x = 0 ;
 pixel_x < 4 ;
 pixel_x ++ ) pixels [ pixel_ptr ++ ] = colors [ 0 ] ;
 pixel_ptr -= row_dec ;
 }
 }
 block_ptr += block_inc ;
 total_blocks -- ;
 }
 }
 if ( s -> avctx -> pix_fmt == AV_PIX_FMT_PAL8 ) memcpy ( s -> frame . data [ 1 ] , s -> pal , AVPALETTE_SIZE ) ;
 }


void EnsureCustomWallpaperDirectories(
    const wallpaper::WallpaperFilesId& wallpaper_files_id) {
  base::FilePath dir;
  dir = WallpaperManagerBase::GetCustomWallpaperDir(kSmallWallpaperSubDir);
  dir = dir.Append(wallpaper_files_id.id());
  if (!base::PathExists(dir))
    base::CreateDirectory(dir);
  dir = WallpaperManagerBase::GetCustomWallpaperDir(kLargeWallpaperSubDir);
  dir = dir.Append(wallpaper_files_id.id());
  if (!base::PathExists(dir))
    base::CreateDirectory(dir);
  dir = WallpaperManagerBase::GetCustomWallpaperDir(kOriginalWallpaperSubDir);
  dir = dir.Append(wallpaper_files_id.id());
  if (!base::PathExists(dir))
    base::CreateDirectory(dir);
  dir = WallpaperManagerBase::GetCustomWallpaperDir(kThumbnailWallpaperSubDir);
  dir = dir.Append(wallpaper_files_id.id());
  if (!base::PathExists(dir))
    base::CreateDirectory(dir);
}


static int init_hyp_mode(void)
{
	int cpu;
	int err = 0;

	/*
	 * Allocate Hyp PGD and setup Hyp identity mapping
	 */
	err = kvm_mmu_init();
	if (err)
		goto out_err;

	/*
	 * It is probably enough to obtain the default on one
	 * CPU. It's unlikely to be different on the others.
	 */
	hyp_default_vectors = __hyp_get_vectors();

	/*
	 * Allocate stack pages for Hypervisor-mode
	 */
	for_each_possible_cpu(cpu) {
		unsigned long stack_page;

		stack_page = __get_free_page(GFP_KERNEL);
		if (!stack_page) {
			err = -ENOMEM;
			goto out_free_stack_pages;
		}

		per_cpu(kvm_arm_hyp_stack_page, cpu) = stack_page;
	}

	/*
	 * Map the Hyp-code called directly from the host
	 */
	err = create_hyp_mappings(__kvm_hyp_code_start, __kvm_hyp_code_end);
	if (err) {
		kvm_err("Cannot map world-switch code\n");
		goto out_free_mappings;
	}

	/*
	 * Map the Hyp stack pages
	 */
	for_each_possible_cpu(cpu) {
		char *stack_page = (char *)per_cpu(kvm_arm_hyp_stack_page, cpu);
		err = create_hyp_mappings(stack_page, stack_page + PAGE_SIZE);

		if (err) {
			kvm_err("Cannot map hyp stack\n");
			goto out_free_mappings;
		}
	}

	/*
	 * Map the host CPU structures
	 */
	kvm_host_cpu_state = alloc_percpu(kvm_cpu_context_t);
	if (!kvm_host_cpu_state) {
		err = -ENOMEM;
		kvm_err("Cannot allocate host CPU state\n");
		goto out_free_mappings;
	}

	for_each_possible_cpu(cpu) {
		kvm_cpu_context_t *cpu_ctxt;

		cpu_ctxt = per_cpu_ptr(kvm_host_cpu_state, cpu);
		err = create_hyp_mappings(cpu_ctxt, cpu_ctxt + 1);

		if (err) {
			kvm_err("Cannot map host CPU state: %d\n", err);
			goto out_free_context;
		}
	}

	/*
	 * Execute the init code on each CPU.
	 */
	on_each_cpu(cpu_init_hyp_mode, NULL, 1);

	/*
	 * Init HYP view of VGIC
	 */
	err = kvm_vgic_hyp_init();
	if (err)
		goto out_free_context;

#ifdef CONFIG_KVM_ARM_VGIC
		vgic_present = true;
#endif

	/*
	 * Init HYP architected timer support
	 */
	err = kvm_timer_hyp_init();
	if (err)
		goto out_free_mappings;

#ifndef CONFIG_HOTPLUG_CPU
	free_boot_hyp_pgd();
#endif

	kvm_perf_init();

	kvm_info("Hyp mode initialized successfully\n");

	return 0;
out_free_context:
	free_percpu(kvm_host_cpu_state);
out_free_mappings:
	free_hyp_pgds();
out_free_stack_pages:
	for_each_possible_cpu(cpu)
		free_page(per_cpu(kvm_arm_hyp_stack_page, cpu));
out_err:
	kvm_err("error initializing Hyp mode: %d\n", err);
	return err;
}


void ChromeRenderMessageFilter::OnWriteTcmallocHeapProfile(
    const FilePath::StringType& filepath,
    const std::string& output) {
  VLOG(0) << "Writing renderer heap profile dump to: " << filepath;
  file_util::WriteFile(FilePath(filepath), output.c_str(), output.size());
}


cJSON *cJSON_DetachItemFromArray(cJSON *array,int which)			{cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0;
	if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;}


SWTPM_NVRAM_GetPlainData(unsigned char **plain, uint32_t *plain_length,
                         const unsigned char *data, uint32_t length,
                         uint16_t tag_data,
                         uint8_t hdrversion)
{
    TPM_RESULT rc = 0;
    tlv_data td[1];

    switch (hdrversion) {
    case 1:
        *plain = malloc(length);
        if (*plain) {
            memcpy(*plain, data, length);
            *plain_length = length;
        } else {
            logprintf(STDERR_FILENO,
                      "Could not allocate %u bytes.\n", length);
            rc = TPM_FAIL;
        }
    break;

    case 2:
        if (!tlv_data_find_tag(data, length, tag_data, &td[0])) {
            logprintf(STDERR_FILENO,
                      "Could not find plain data in byte stream.\n");
            rc = TPM_FAIL;
            break;
        }
        *plain = malloc(td->tlv.length);
        if (*plain) {
            memcpy(*plain, td->u.const_ptr, td->tlv.length);
            *plain_length = td->tlv.length;
        } else {
            logprintf(STDERR_FILENO,
                      "Could not allocate %u bytes.\n", td->tlv.length);
            rc = TPM_FAIL;
        }
    break;
    }

    return rc;
}


static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result)

{

    return qcow2_check_refcounts(bs, result);

}


static int of_dpa_cmd_group_add(OfDpa *of_dpa, uint32_t group_id,

                                RockerTlv **group_tlvs)

{

    OfDpaGroup *group = of_dpa_group_find(of_dpa, group_id);

    int err;

    if (group) {

        return -ROCKER_EEXIST;

    }

    group = of_dpa_group_alloc(group_id);

    if (!group) {

        return -ROCKER_ENOMEM;

    }

    err = of_dpa_cmd_group_do(of_dpa, group_id, group, group_tlvs);

    if (err) {

        goto err_cmd_add;

    }

    err = of_dpa_group_add(of_dpa, group);

    if (err) {

        goto err_cmd_add;

    }

    return ROCKER_OK;

err_cmd_add:

    g_free(group);

    return err;

}


static int mem_open(struct inode *inode, struct file *file)
{
	int ret = __mem_open(inode, file, PTRACE_MODE_ATTACH);

	/* OK to pass negative loff_t, we can catch out-of-range */
	file->f_mode |= FMODE_UNSIGNED_OFFSET;

	return ret;
}


struct qtmd_stream * qtmd_init ( struct mspack_system * system , struct mspack_file * input , struct mspack_file * output , int window_bits , int input_buffer_size ) {
 unsigned int window_size = 1 << window_bits ;
 struct qtmd_stream * qtm ;
 int i ;
 if ( ! system ) return NULL ;
 if ( window_bits < 10 || window_bits > 21 ) return NULL ;
 input_buffer_size = ( input_buffer_size + 1 ) & - 2 ;
 if ( input_buffer_size < 2 ) return NULL ;
 if ( ! ( qtm = ( struct qtmd_stream * ) system -> alloc ( system , sizeof ( struct qtmd_stream ) ) ) ) {
 return NULL ;
 }
 qtm -> window = ( unsigned char * ) system -> alloc ( system , ( size_t ) window_size ) ;
 qtm -> inbuf = ( unsigned char * ) system -> alloc ( system , ( size_t ) input_buffer_size ) ;
 if ( ! qtm -> window || ! qtm -> inbuf ) {
 system -> free ( qtm -> window ) ;
 system -> free ( qtm -> inbuf ) ;
 system -> free ( qtm ) ;
 return NULL ;
 }
 qtm -> sys = system ;
 qtm -> input = input ;
 qtm -> output = output ;
 qtm -> inbuf_size = input_buffer_size ;
 qtm -> window_size = window_size ;
 qtm -> window_posn = 0 ;
 qtm -> frame_todo = QTM_FRAME_SIZE ;
 qtm -> header_read = 0 ;
 qtm -> error = MSPACK_ERR_OK ;
 qtm -> i_ptr = qtm -> i_end = & qtm -> inbuf [ 0 ] ;
 qtm -> o_ptr = qtm -> o_end = & qtm -> window [ 0 ] ;
 qtm -> input_end = 0 ;
 qtm -> bits_left = 0 ;
 qtm -> bit_buffer = 0 ;
 i = window_bits * 2 ;
 qtmd_init_model ( & qtm -> model0 , & qtm -> m0sym [ 0 ] , 0 , 64 ) ;
 qtmd_init_model ( & qtm -> model1 , & qtm -> m1sym [ 0 ] , 64 , 64 ) ;
 qtmd_init_model ( & qtm -> model2 , & qtm -> m2sym [ 0 ] , 128 , 64 ) ;
 qtmd_init_model ( & qtm -> model3 , & qtm -> m3sym [ 0 ] , 192 , 64 ) ;
 qtmd_init_model ( & qtm -> model4 , & qtm -> m4sym [ 0 ] , 0 , ( i > 24 ) ? 24 : i ) ;
 qtmd_init_model ( & qtm -> model5 , & qtm -> m5sym [ 0 ] , 0 , ( i > 36 ) ? 36 : i ) ;
 qtmd_init_model ( & qtm -> model6 , & qtm -> m6sym [ 0 ] , 0 , i ) ;
 qtmd_init_model ( & qtm -> model6len , & qtm -> m6lsym [ 0 ] , 0 , 27 ) ;
 qtmd_init_model ( & qtm -> model7 , & qtm -> m7sym [ 0 ] , 0 , 7 ) ;
 return qtm ;
 }


  net::ProxyServer origin() const {
    return config()->test_params()->proxies_for_http().front().proxy_server();
  }


int CountScreenshots() {
  DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
      ProfileManager::GetActiveUserProfile());
  base::FileEnumerator enumerator(download_prefs->DownloadPath(),
                                  false, base::FileEnumerator::FILES,
                                  "Screenshot*");
  int count = 0;
  while (!enumerator.Next().empty())
    count++;
  return count;
}


flatpak_transaction_add_rebase (FlatpakTransaction *self,
                                const char         *remote,
                                const char         *ref,
                                const char        **subpaths,
                                const char        **previous_ids,
                                GError            **error)
{
  FlatpakTransactionPrivate *priv = flatpak_transaction_get_instance_private (self);
  const char *all_paths[] = { NULL };
  g_autoptr(FlatpakDecomposed) decomposed = NULL;
  g_autofree char *installed_origin = NULL;

  g_return_val_if_fail (ref != NULL, FALSE);
  g_return_val_if_fail (remote != NULL, FALSE);
  /* flatpak_transaction_add_rebase without previous_ids doesn't make sense */
  g_return_val_if_fail (previous_ids != NULL, FALSE);

  decomposed = flatpak_decomposed_new_from_ref (ref, error);
  if (decomposed == NULL)
    return FALSE;

  /* If we install with no special args pull all subpaths */
  if (subpaths == NULL)
    subpaths = all_paths;

  if (dir_ref_is_installed (priv->dir, decomposed, &installed_origin, NULL))
    remote = installed_origin;

  return flatpak_transaction_add_ref (self, remote, decomposed, subpaths, previous_ids, NULL, FLATPAK_TRANSACTION_OPERATION_INSTALL_OR_UPDATE, NULL, NULL, FALSE, error);
}


static struct iscsi_param *__iscsi_check_key(
	char *key,
	int sender,
	struct iscsi_param_list *param_list)
{
	struct iscsi_param *param;

	if (strlen(key) > KEY_MAXLEN) {
		pr_err("Length of key name \"%s\" exceeds %d.\n",
			key, KEY_MAXLEN);
		return NULL;
	}

	param = iscsi_find_param_from_key(key, param_list);
	if (!param)
		return NULL;

	if ((sender & SENDER_INITIATOR) && !IS_SENDER_INITIATOR(param)) {
		pr_err("Key \"%s\" may not be sent to %s,"
			" protocol error.\n", param->name,
			(sender & SENDER_RECEIVER) ? "target" : "initiator");
		return NULL;
	}

	if ((sender & SENDER_TARGET) && !IS_SENDER_TARGET(param)) {
		pr_err("Key \"%s\" may not be sent to %s,"
			" protocol error.\n", param->name,
			(sender & SENDER_RECEIVER) ? "initiator" : "target");
		return NULL;
	}

	return param;
}


char *to_utf8(size_t len, char *buf) {
  int i, j = 0;
  /* worst case length */
  if (len > 10000) {	// deal with this by adding an arbitrary limit
     printf("suspecting a corrupt file in UTF8 conversion\n");
     exit(-1);
  }
  char *utf8 = malloc(3 * len / 2 + 1);

  for (i = 0; i < len - 1; i += 2) {
    unsigned int c = SwapWord((BYTE *)buf + i, 2);
    if (c <= 0x007f) {
      utf8[j++] = 0x00 | ((c & 0x007f) >> 0);
    } else if (c < 0x07ff) {
      utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6);
      utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
    } else {
      utf8[j++] = 0xe0 | ((c & 0xf000) >> 12);
      utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6);
      utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
    }
  }

  /* just in case the original was not null terminated */
  utf8[j++] = '\0';

  return utf8;
}


void WebLocalFrameImpl::SaveImageAt(const WebPoint& pos_in_viewport) {
  Node* node = HitTestResultForVisualViewportPos(pos_in_viewport)
                   .InnerNodeOrImageMapImage();
  if (!node || !(IsHTMLCanvasElement(*node) || IsHTMLImageElement(*node)))
    return;

  String url = ToElement(*node).ImageSourceURL();
  if (!KURL(NullURL(), url).ProtocolIsData())
    return;

  client_->SaveImageFromDataURL(url);
}


static void install_list_entry(const char *lib) {
	assert(lib);

	// filename check
	int len = strlen(lib);
	if (strcspn(lib, "\\&!?\"'<>%^(){}[];,") != (size_t)len ||
	strstr(lib, "..")) {
		fprintf(stderr, "Error: \"%s\" is an invalid library\n", lib);
		exit(1);
	}

	// if this is a full path, use it as is
	if (*lib == '/')
		return load_library(lib);

	// find the library
	int i;
	for (i = 0; default_lib_paths[i]; i++) {
		char *fname = NULL;
		if (asprintf(&fname, "%s/%s", default_lib_paths[i], lib) == -1)
			errExit("asprintf");

#define DO_GLOBBING
#ifdef DO_GLOBBING
		// globbing
		glob_t globbuf;
		int globerr = glob(fname, GLOB_NOCHECK | GLOB_NOSORT | GLOB_PERIOD, NULL, &globbuf);
		if (globerr) {
			fprintf(stderr, "Error: failed to glob private-lib pattern %s\n", fname);
			exit(1);
		}
		size_t j;
		for (j = 0; j < globbuf.gl_pathc; j++) {
			assert(globbuf.gl_pathv[j]);
//printf("glob %s\n", globbuf.gl_pathv[j]);
			// GLOB_NOCHECK - no pattern matched returns the original pattern; try to load it anyway
			load_library(globbuf.gl_pathv[j]);
		}

		globfree(&globbuf);
#else
		load_library(fname);
#endif
		free(fname);
	}

//	fwarning("%s library not found, skipping...\n", lib);
	return;
}


struct btd_adapter *adapter_find_by_id(int id)
{
	GSList *match;

	match = g_slist_find_custom(adapters, GINT_TO_POINTER(id),
							adapter_id_cmp);
	if (!match)
		return NULL;

	return match->data;
}


static void gen_bpt_io(DisasContext *s, TCGv_i32 t_port, int ot)
{
    if (s->flags & HF_IOBPT_MASK) {
        TCGv_i32 t_size = tcg_const_i32(1 << ot);
        TCGv t_next = tcg_const_tl(s->pc - s->cs_base);

        gen_helper_bpt_io(cpu_env, t_port, t_size, t_next);
        tcg_temp_free_i32(t_size);
        tcg_temp_free(t_next);
    }
}


void WebContentsImpl::RequestFindMatchRects(int current_version) {
  GetOrCreateFindRequestManager()->RequestFindMatchRects(current_version);
}


ScriptLoader::~ScriptLoader()
{
    stopLoadRequest();
}


ImmutableExecutorState::FrameInfo* ImmutableExecutorState::EnsureFrameInfo(
    const string& fname) {
  auto iter = frame_info_.find(fname);
  if (iter != frame_info_.end()) {
    return iter->second.get();
  } else {
    auto frame_info = absl::make_unique<FrameInfo>(fname);
    absl::string_view fname_view = frame_info->name;
    auto emplace_result =
        frame_info_.emplace(fname_view, std::move(frame_info));
    return emplace_result.first->second.get();
  }
}


RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host)
    : host_(RenderWidgetHostImpl::From(host)),
      ALLOW_THIS_IN_INITIALIZER_LIST(window_(new aura::Window(this))),
      in_shutdown_(false),
      is_fullscreen_(false),
      popup_parent_host_view_(NULL),
      popup_child_host_view_(NULL),
      is_loading_(false),
      text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
      can_compose_inline_(true),
       has_composition_text_(false),
       device_scale_factor_(1.0f),
       current_surface_(0),
       paint_canvas_(NULL),
       synthetic_move_sent_(false),
       accelerated_compositing_state_changed_(false),
      can_lock_compositor_(YES) {
  host_->SetView(this);
  window_observer_.reset(new WindowObserver(this));
  window_->AddObserver(window_observer_.get());
  aura::client::SetTooltipText(window_, &tooltip_);
  aura::client::SetActivationDelegate(window_, this);
  gfx::Screen::GetScreenFor(window_)->AddObserver(this);
}


static int vhdx_log_write(BlockDriverState *bs, BDRVVHDXState *s,

                          void *data, uint32_t length, uint64_t offset)

{

    int ret = 0;

    void *buffer = NULL;

    void *merged_sector = NULL;

    void *data_tmp, *sector_write;

    unsigned int i;

    int sector_offset;

    uint32_t desc_sectors, sectors, total_length;

    uint32_t sectors_written = 0;

    uint32_t aligned_length;

    uint32_t leading_length = 0;

    uint32_t trailing_length = 0;

    uint32_t partial_sectors = 0;

    uint32_t bytes_written = 0;

    uint64_t file_offset;

    VHDXHeader *header;

    VHDXLogEntryHeader new_hdr;

    VHDXLogDescriptor *new_desc = NULL;

    VHDXLogDataSector *data_sector = NULL;

    MSGUID new_guid = { 0 };

    header = s->headers[s->curr_header];

    /* need to have offset read data, and be on 4096 byte boundary */

    if (length > header->log_length) {

        /* no log present.  we could create a log here instead of failing */

        ret = -EINVAL;

        goto exit;

    }

    if (guid_eq(header->log_guid, zero_guid)) {

        vhdx_guid_generate(&new_guid);

        vhdx_update_headers(bs, s, false, &new_guid);

    } else {

        /* currently, we require that the log be flushed after

         * every write. */

        ret = -ENOTSUP;

        goto exit;

    }

    /* 0 is an invalid sequence number, but may also represent the first

     * log write (or a wrapped seq) */

    if (s->log.sequence == 0) {

        s->log.sequence = 1;

    }

    sector_offset = offset % VHDX_LOG_SECTOR_SIZE;

    file_offset = (offset / VHDX_LOG_SECTOR_SIZE) * VHDX_LOG_SECTOR_SIZE;

    aligned_length = length;

    /* add in the unaligned head and tail bytes */

    if (sector_offset) {

        leading_length = (VHDX_LOG_SECTOR_SIZE - sector_offset);

        leading_length = leading_length > length ? length : leading_length;

        aligned_length -= leading_length;

        partial_sectors++;

    }

    sectors = aligned_length / VHDX_LOG_SECTOR_SIZE;

    trailing_length = aligned_length - (sectors * VHDX_LOG_SECTOR_SIZE);

    if (trailing_length) {

        partial_sectors++;

    }

    sectors += partial_sectors;

    /* sectors is now how many sectors the data itself takes, not

     * including the header and descriptor metadata */

    new_hdr = (VHDXLogEntryHeader) {

                .signature           = VHDX_LOG_SIGNATURE,

                .tail                = s->log.tail,

                .sequence_number     = s->log.sequence,

                .descriptor_count    = sectors,

                .reserved            = 0,

                .flushed_file_offset = bdrv_getlength(bs->file->bs),

                .last_file_offset    = bdrv_getlength(bs->file->bs),

              };

    new_hdr.log_guid = header->log_guid;

    desc_sectors = vhdx_compute_desc_sectors(new_hdr.descriptor_count);

    total_length = (desc_sectors + sectors) * VHDX_LOG_SECTOR_SIZE;

    new_hdr.entry_length = total_length;

    vhdx_log_entry_hdr_le_export(&new_hdr);

    buffer = qemu_blockalign(bs, total_length);

    memcpy(buffer, &new_hdr, sizeof(new_hdr));

    new_desc = buffer + sizeof(new_hdr);

    data_sector = buffer + (desc_sectors * VHDX_LOG_SECTOR_SIZE);

    data_tmp = data;

    /* All log sectors are 4KB, so for any partial sectors we must

     * merge the data with preexisting data from the final file

     * destination */

    merged_sector = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);

    for (i = 0; i < sectors; i++) {

        new_desc->signature       = VHDX_LOG_DESC_SIGNATURE;

        new_desc->sequence_number = s->log.sequence;

        new_desc->file_offset     = file_offset;

        if (i == 0 && leading_length) {

            /* partial sector at the front of the buffer */

            ret = bdrv_pread(bs->file, file_offset, merged_sector,

                             VHDX_LOG_SECTOR_SIZE);

            if (ret < 0) {

                goto exit;

            }

            memcpy(merged_sector + sector_offset, data_tmp, leading_length);

            bytes_written = leading_length;

            sector_write = merged_sector;

        } else if (i == sectors - 1 && trailing_length) {

            /* partial sector at the end of the buffer */

            ret = bdrv_pread(bs->file,

                            file_offset,

                            merged_sector + trailing_length,

                            VHDX_LOG_SECTOR_SIZE - trailing_length);

            if (ret < 0) {

                goto exit;

            }

            memcpy(merged_sector, data_tmp, trailing_length);

            bytes_written = trailing_length;

            sector_write = merged_sector;

        } else {

            bytes_written = VHDX_LOG_SECTOR_SIZE;

            sector_write = data_tmp;

        }

        /* populate the raw sector data into the proper structures,

         * as well as update the descriptor, and convert to proper

         * endianness */

        vhdx_log_raw_to_le_sector(new_desc, data_sector, sector_write,

                                  s->log.sequence);

        data_tmp += bytes_written;

        data_sector++;

        new_desc++;

        file_offset += VHDX_LOG_SECTOR_SIZE;

    }

    /* checksum covers entire entry, from the log header through the

     * last data sector */

    vhdx_update_checksum(buffer, total_length,

                         offsetof(VHDXLogEntryHeader, checksum));

    /* now write to the log */

    ret = vhdx_log_write_sectors(bs, &s->log, &sectors_written, buffer,

                                 desc_sectors + sectors);

    if (ret < 0) {

        goto exit;

    }

    if (sectors_written != desc_sectors + sectors) {

        /* instead of failing, we could flush the log here */

        ret = -EINVAL;

        goto exit;

    }

    s->log.sequence++;

    /* write new tail */

    s->log.tail = s->log.write;

exit:

    qemu_vfree(buffer);

    qemu_vfree(merged_sector);

    return ret;

}


static inline void t_gen_sext(TCGv d, TCGv s, int size)

{

	if (size == 1)

		tcg_gen_ext8s_i32(d, s);

	else if (size == 2)

		tcg_gen_ext16s_i32(d, s);

	else if(GET_TCGV(d) != GET_TCGV(s))

		tcg_gen_mov_tl(d, s);

}


void BrowserLauncherItemController::UpdateLauncher(TabContents* tab) {
  if (type() == TYPE_APP_PANEL)
    return;  // Maintained entirely by ChromeLauncherController.

  if (!tab)
    return;  // Assume the window is going to be closed if there are no tabs.

  int item_index = launcher_model()->ItemIndexByID(launcher_id());
  if (item_index == -1)
    return;

  ash::LauncherItem item = launcher_model()->items()[item_index];
  if (type() == TYPE_EXTENSION_PANEL) {
    if (!favicon_loader_.get() ||
        favicon_loader_->web_contents() != tab->web_contents()) {
      favicon_loader_.reset(
          new LauncherFaviconLoader(this, tab->web_contents()));
    }
    extensions::TabHelper* extensions_tab_helper =
        extensions::TabHelper::FromWebContents(tab->web_contents());
    gfx::ImageSkia new_image = gfx::ImageSkia(favicon_loader_->GetFavicon());
    if (new_image.isNull() && extensions_tab_helper->GetExtensionAppIcon())
      new_image = gfx::ImageSkia(*extensions_tab_helper->GetExtensionAppIcon());
    if (!new_image.isNull())
      item.image = new_image;
    else if (item.image.isNull())
      item.image = extensions::Extension::GetDefaultIcon(true);
  } else {
    DCHECK_EQ(TYPE_TABBED, type());
    ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
    FaviconTabHelper* favicon_tab_helper =
        FaviconTabHelper::FromWebContents(tab->web_contents());
    if (favicon_tab_helper->ShouldDisplayFavicon()) {
      item.image = favicon_tab_helper->GetFavicon().AsImageSkia();
      if (item.image.isNull()) {
        item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON);
      }
    } else {
      item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON);
    }
  }
  launcher_model()->Set(item_index, item);
}


static int handle_packets(MpegTSContext *ts, int nb_packets)

{

    AVFormatContext *s = ts->stream;

    uint8_t packet[TS_PACKET_SIZE];

    int packet_num, ret = 0;

    if (avio_tell(s->pb) != ts->last_pos) {

        int i;

        av_dlog("Skipping after seek\n");

        /* seek detected, flush pes buffer */

        for (i = 0; i < NB_PID_MAX; i++) {

            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {

                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;

                av_freep(&pes->buffer);

                ts->pids[i]->last_cc = -1;

                pes->data_index = 0;

                pes->state = MPEGTS_SKIP; /* skip until pes header */

            }

        }

    }

    ts->stop_parse = 0;

    packet_num = 0;

    for(;;) {

        if (ts->stop_parse>0)

            break;

        packet_num++;

        if (nb_packets != 0 && packet_num >= nb_packets)

            break;

        ret = read_packet(s, packet, ts->raw_packet_size);

        if (ret != 0)

            break;

        ret = handle_packet(ts, packet);

        if (ret != 0)

            break;

    }

    ts->last_pos = avio_tell(s->pb);

    return ret;

}


static int br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
	struct net_device *dev;
	struct net *net = sock_net(skb->sk);
	struct nlmsghdr *nlh = NULL;
	int idx = 0, s_idx;

	s_idx = cb->args[0];

	rcu_read_lock();

	/* In theory this could be wrapped to 0... */
	cb->seq = net->dev_base_seq + br_mdb_rehash_seq;

	for_each_netdev_rcu(net, dev) {
		if (dev->priv_flags & IFF_EBRIDGE) {
			struct br_port_msg *bpm;

			if (idx < s_idx)
				goto skip;

			nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid,
					cb->nlh->nlmsg_seq, RTM_GETMDB,
					sizeof(*bpm), NLM_F_MULTI);
			if (nlh == NULL)
				break;

			bpm = nlmsg_data(nlh);
			memset(bpm, 0, sizeof(*bpm));
			bpm->ifindex = dev->ifindex;
			if (br_mdb_fill_info(skb, cb, dev) < 0)
				goto out;
			if (br_rports_fill_info(skb, cb, dev) < 0)
				goto out;

			cb->args[1] = 0;
			nlmsg_end(skb, nlh);
		skip:
			idx++;
		}
	}

out:
	if (nlh)
		nlmsg_end(skb, nlh);
	rcu_read_unlock();
	cb->args[0] = idx;
	return skb->len;
}


StringData* detach() { return m_str.detach(); }


static inline int is_thumb(struct PE_(r_bin_pe_obj_t)* bin) {
	return bin->nt_headers->optional_header.AddressOfEntryPoint & 1;
}